使用地理位置和Google Maps API创建折线

“使用Google Maps API获取路线”中 ,我解释了如何创建一种服务,该服务可使用户找到从一个地址到另一个地址的路线。 在本文中,您将学习如何结合使用Geolocation API和Google Maps API在连接多个点的地图上显示折线。

本文假定您熟悉使用地理定位和Google Maps API使用 Google Maps API 获取路线中的内容 。 如果您还没有阅读它们,我建议您现在阅读。

利用Google Maps API做更多的事情

在前两篇文章中,您已经看到了许多类,方法和属性,但是,它们只是Google Maps API难题的一小部分。 在本部分中,您将看到我们在最终演示中使用的另一部分API。

我将介绍的第一堂课是google.maps.Polyline 。 它使用传递给构造函数的选项(一个google.maps.PolylineOptions对象)绘制一条连接多个点的线。 此类的方法只是getter和setter,所以我不会赘述,但是请记住,最重要的setter是setPath()setMap()setPath()定义要连接的点, setMap()绘制线条的地图。

google.maps.PolylineOptions类充满了可用于调整折线以适合您需要的属性。 两个最重要的是那些之前描述的制定者根本- mappath 。 笔画属性也值得注意,因为它们将在演示中使用。 顾名思义, strokeColor设置描边颜色,默认为#000000 (黑色)。 strokeOpacity是介于0.0和1.0之间的数字,用于设置笔触的不透明度。 strokeWeight是一个数字,以像素为单位设置笔划宽度。 我建议阅读PolylineOptions官方文档以了解其他有用的属性。

该演示还利用了google.maps.LatLngBounds类。 引用官方文档LatLngBounds代表地理坐标中的矩形,包括一个与180度纵向子午线交叉的矩形 。 其构造函数最多接受两个参数,如果给定,则必须是LatLng实例。 第一个用作矩形的西南点,第二个用作东北点。 在演示中,您将看到的唯一方法是extend() ,它接受LatLng点,并加宽当前矩形的边界以包括该点。 LatLngBounds类的另一种方法是contains() ,它测试LatLng坐标是否在范围内。 此类还具有其他可用于多个矩形的有用方法。 实际上,您可以合并( union() )或相交( intersects() )矩形,但是请记住,一次只能在两个LatLngBounds实例上运行该动作。

构建演示

为了查看所展示的类的实际效果,让我们构建一个演示来保存用户的动作,并绘制一条折线,将它们连接到地图上。 因为我们必须跟踪用户的运动,所以该演示使用了watchPosition()方法而不是getCurrentPosition() 。 这些位置将存储在一个名为path的变量中,该变量被初始化为一个空数组。

// Save the positions' history
var path = [];

watchPosition()方法运行成功回调函数时,将使用用户的纬度和经度来构建google.maps.LatLng对象。 然后将该对象插入path数组。 并且,对于添加的每个新点,将刷新地图以显示用户的移动。

// Save the current position
path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));

我们还需要调整地图视图,使其包含折线的所有点。 这是通过将LatLngBounds对象存储在名为latLngBounds的变量中来latLngBounds 。 我们需要遍历所有保存的点,并将它们一次传递给extend()方法。 请注意,目前,我们仅准备将数据与fitBounds()方法配合使用,因此当前地图无法适应边界。 此外,我们还将使用Marker对象标记每个点,以便您可以轻松定位每个位置。 下面列出了实现此目的的代码。

// Create the LatLngBounds object that will be used to fit the view to the points range and
// place the markers to the polyline's points
var latLngBounds = new google.maps.LatLngBounds();
for(var i = 0; i < path.length; i++) {
  latLngBounds.extend(path[i]);
  // Place the marker
  new google.maps.Marker({
    map: map,
    position: path[i],
    title: "Point " + (i + 1)
  });
}

一旦显示了要点,我们就需要使用前面讨论的PolylinePolylineOptions类来构建折线。 这非常容易,因为您只需要使用所需的选项创建一个新的Polyline对象。 在下面的代码中,线条的笔触已更改为一条1像素宽的蓝线,具有70%的不透明度。

// Creates the polyline object
var polyline = new google.maps.Polyline({
  map: map,
  path: path,
  strokeColor: '#0000FF',
  strokeOpacity: 0.7,
  strokeWeight: 1
});

剩下的唯一步骤是确保地图视图包含折线的所有点。 这是通过将latLngBounds变量传递到latLngBoundsfitBounds()方法来完成的,如下所示。

// Fit the bounds of the generated points
map.fitBounds(latLngBounds);

添加预设点

使用上面的代码,我们有一个完全正常的演示。 但是,如果在桌面环境中测试代码,则watchPosition()方法将仅运行一次,因此您将看不到绘制的任何线。 为避免此问题,您可以复制以下代码并将其粘贴到循环遍历path数组并构建LatLngBounds对象的块之前。 该代码将简单地创建一组使用用户当前位置的随机生成的点,并将其插入到path数组中。

// Create the polyline's points
for(var i = 0; i < 5; i++) {
  // Create a random point using the user current position and a random generated number.
  // The number will be once positive and once negative using based on the parity of i
  // and to reduce the range the number is divided by 10
  path.push(
    new google.maps.LatLng(
      position.coords.latitude + (Math.random() / 10 * ((i % 2) ? 1 : -1)),
      position.coords.longitude + (Math.random() / 10 * ((i % 2) ? 1 : -1))
    )
  );
}

演示页

使用前面几节中显示的代码,最后列出了演示工作页面。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Create a polyline using Geolocation and Google Maps API</title>
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        // If the browser supports the Geolocation API
        if (typeof navigator.geolocation == "undefined") {
          $("#error").text("Your browser doesn't support the Geolocation API");
          return;
        }
        // Save the positions' history
        var path = [];

        navigator.geolocation.watchPosition(function(position) {
          // Save the current position
          path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));

          // Create the map
          var myOptions = {
            zoom : 16,
            center : path[0],
            mapTypeId : google.maps.MapTypeId.ROADMAP
          }
          var map = new google.maps.Map(document.getElementById("map"), myOptions);

          /*
          Uncomment this block if you want to set a path

          // Create the polyline's points
          for(var i = 0; i < 5; i++) {
            // Create a random point using the user current position and a random generated number.
            // The number will be once positive and once negative using based on the parity of i
            // and to reduce the range the number is divided by 10
            path.push(
              new google.maps.LatLng(
                position.coords.latitude + (Math.random() / 10 * ((i % 2) ? 1 : -1)),
                position.coords.longitude + (Math.random() / 10 * ((i % 2) ? 1 : -1))
              )
            );
          }
          */

          // Create the array that will be used to fit the view to the points range and
          // place the markers to the polyline's points
          var latLngBounds = new google.maps.LatLngBounds();
          for(var i = 0; i < path.length; i++) {
            latLngBounds.extend(path[i]);
            // Place the marker
            new google.maps.Marker({
              map: map,
              position: path[i],
              title: "Point " + (i + 1)
            });
          }
          // Creates the polyline object
          var polyline = new google.maps.Polyline({
            map: map,
            path: path,
            strokeColor: '#0000FF',
            strokeOpacity: 0.7,
            strokeWeight: 1
          });
          // Fit the bounds of the generated points
          map.fitBounds(latLngBounds);
        },
        function(positionError){
          $("#error").append("Error: " + positionError.message + "<br />");
        },
        {
          enableHighAccuracy: true,
          timeout: 10 * 1000 // 10 seconds
        });
      });
    </script>
    <style type="text/css">
      #map {
        width: 500px;
        height: 400px;
        margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <h1>Create a polyline</h1>
    <div id="map"></div>
    <p id="error"></p>
  </body>
</html>

结论

本文介绍了用于绘制连接地图上多个点的折线的类,属性和方法。 正如您在本系列文章中所看到的那样,这些API可用于构建许多出色的服务,从而改善用户体验。 当然,您可以做的比这里显示的还要多。 通过探索Google Maps API中的其他类,可能性几乎是无限的。

From: https://www.sitepoint.com/create-a-polyline-using-the-geolocation-and-the-google-maps-api/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值