javascript - 使用 Google Maps API 绘制 map 路径/航路点并播放路线

标签 javascript google-maps google-maps-api-3 plot

我正在尝试在播放映射路线时绘制已访问的路径,如以下示例所示:

加载 map 时,我希望绘制的点 A、B、C、D、E 和 F 一个接一个地连接起来。

我已经成功地绘制了这些点,但是我不能一个接一个地动态链接这些点。

这是我的代码:

<script type="text/javascript">
var markers = [{
    "title": 'Alibaug',
    "lat": '12.97721863',
    "lng": '80.22206879',
    "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}, {
    "title": 'Mumbai',
    "lat": '12.9962529',
    "lng": '80.2570098',
    "description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
}, {
    "title": 'Pune',
    "lat": '12.97722816',
    "lng": '80.22219086',
    "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}];
window.onload = function() {
    var mapOptions = {
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP,};
    var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);

    //*********** GOOGLE MAP SEARCH ****************//
    // Create the search box and link it to the UI element.
    var input = /** @type {HTMLInputElement} */ (
        document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var searchBox = new google.maps.places.SearchBox(
        /** @type {HTMLInputElement} */
        (input));
    // Listen for the event fired when the user selects an item from the
    // pick list. Retrieve the matching places for that item.
    google.maps.event.addListener(searchBox, 'places_changed', function() {
        var places = searchBox.getPlaces();

        for (var i = 0, marker; marker = markers[i]; i++) {
            // marker.setMap(null);
        }

        // For each place, get the icon, place name, and location.
        markers = [];
        var bounds = new google.maps.LatLngBounds();
        var place = null;
        var viewport = null;
        for (var i = 0; place = places[i]; i++) {
            var image = {
                url: place.icon,
                size: new google.maps.Size(71, 71),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(17, 34),
                scaledSize: new google.maps.Size(25, 25)
            };

            // Create a marker for each place.
            var marker = new google.maps.Marker({
                map: map,
                icon: image,
                title: place.name,
                position: place.geometry.location
            });
            viewport = place.geometry.viewport;
            markers.push(marker);

            bounds.extend(place.geometry.location);
        }
        map.setCenter(bounds.getCenter());
    });
    // Bias the SearchBox results towards places that are within the bounds of the
    // current map's viewport.
    google.maps.event.addListener(map, 'bounds_changed', function() {
        var bounds = map.getBounds();
        searchBox.setBounds(bounds);
    });
    //***********Google Map Search Ends****************//


    var infoWindow = new google.maps.InfoWindow();
    var lat_lng = new Array();
    var latlngbounds = new google.maps.LatLngBounds();
    for (i = 0; i < markers.length; i++) {
        var data = markers[i]
        var myLatlng = new google.maps.LatLng(data.lat, data.lng);
        lat_lng.push(myLatlng);
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: data.title
        });
        latlngbounds.extend(marker.position);
        (function(marker, data) {
            google.maps.event.addListener(marker, "click", function(e) {
                infoWindow.setContent(data.description);
                infoWindow.open(map, marker);
            });
        })(marker, data);
    }
    map.setCenter(latlngbounds.getCenter());
    map.fitBounds(latlngbounds);

    //***********ROUTING****************//

    //Initialize the Path Array
    var path = new google.maps.MVCArray();

    //Initialize the Direction Service
    var service = new google.maps.DirectionsService();

    //Set the Path Stroke Color
    var poly = new google.maps.Polyline({
        map: map,
        strokeColor: '#4986E7'
    });

    //Loop and Draw Path Route between the Points on MAP
    for (var i = 0; i < lat_lng.length; i++) {
        if ((i + 1) < lat_lng.length) {
            var src = lat_lng[i];
            var des = lat_lng[i + 1];
            path.push(src);
            poly.setPath(path);
            service.route({
                origin: src,
                destination: des,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            }, function(result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                        path.push(result.routes[0].overview_path[i]);
                    }
                }
            });
        }
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}

输出类似于: Google map showing points along a route

我如何回放显示这条 map 路线上的点?有没有实例?

最佳答案

https://duncan99.wordpress.com/2015/01/22/animated-paths-with-google-maps/ 有一篇很好的博文和示例代码解释如何为路线设置动画。

该示例与您的问题之间的区别在于您的 route 有路标。您可以使用路标一次获取整个路线,也可以像在上面的代码中那样获取路线。我在下面包含了一个使用航路点的编码片段(免费版本的谷歌地图最多 8 个)。如果您在代码中使用该方法,则需要确保在开始动画之前已加载整个路径。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Map Example</title>
</head>

<body>
  <button id="animate">Redo Animation</button>
  <div id="map_canvas" style="width: 600px;height: 600px"></div>
  <script type="text/javascript">
    var markers = [{
      "title": 'Alibaug',
      "lat": '18.6581725',
      "lng": '72.8637616',
      "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
    }, {
      "title": 'Mumbai',
      "lat": '19.0458547',
      "lng": '72.9434202',
      "description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
    }, {
      "title": 'Pune',
      "lat": '18.5247663',
      "lng": '73.7929273',
      "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
    }];

    function animatePath(map, route, marker, pathCoords) {
      var index = 0;
      route.setPath([]);
      for (var index = 0; index < pathCoords.length; index++)
        setTimeout(function(offset) {
          route.getPath().push(pathCoords.getAt(offset));
          marker.setPosition(pathCoords.getAt(offset));
          map.panTo(pathCoords.getAt(offset));
        }, index * 30, index);
    }

    function initialize() {

      var mapOptions = {
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
        zoom: 20,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

      var infoWindow = new google.maps.InfoWindow();
      var latlngbounds = new google.maps.LatLngBounds();
      for (i = 0; i < markers.length; i++) {
        var data = markers[i];
        markers[i].latLng = new google.maps.LatLng(data.lat, data.lng);
        var marker = new google.maps.Marker({
          position: markers[i].latLng,
          map: map,
          title: data.title
        });
        marker.description = markers[i].description;
        latlngbounds.extend(marker.position);
        google.maps.event.addListener(marker, "click", function(e) {
          infoWindow.setContent(this.description);
          infoWindow.open(map, this);
        });
      }
      map.setCenter(latlngbounds.getCenter());
      map.fitBounds(latlngbounds);

      //Initialize the Path Array
      var path = new google.maps.MVCArray();

      //Initialize the Direction Service
      var service = new google.maps.DirectionsService();

      // Get the route between the points on the map
      var wayPoints = [];
      for (var i = 1; i < markers.length - 1; i++) {
        wayPoints.push({
          location: markers[i].latLng,
          stopover: false
        });
      }
      //Initialize the path
      var poly = new google.maps.Polyline({
        map: map,
        strokeColor: '#4986E7'
      });
      var traceMarker = new google.maps.Marker({
        map: map,
        icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
      });

      if (markers.length >= 2) {
        service.route({
          origin: markers[0].latLng,
          destination: markers[markers.length - 1].latLng,
          waypoints: wayPoints,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
        }, function(result, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            for (var j = 0, len = result.routes[0].overview_path.length; j < len; j++) {
              path.push(result.routes[0].overview_path[j]);
            }
            animatePath(map, poly, traceMarker, path);
          }
        });
      }

      document.getElementById("animate").addEventListener("click", function() {
        // Animate the path when the button is clicked
        animatePath(map, poly, traceMarker, path);
      });

    };
  </script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
</body>

</html>

关于javascript - 使用 Google Maps API 绘制 map 路径/航路点并播放路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36846983/

相关文章:

swift - 从 CLLocationManager (Google Maps API) 获取用户位置的问题

javascript - 根据三个标记的坐标制作圆圈

javascript - 在松散类型语言的单元测试中,是否应该检查方法的返回类型?

javascript - 如何使用requirejs递归加载目录?

javascript - 如何从 GGeoXml 对象获取 KML 数据

javascript - 本地化谷歌地图平移提示

google-maps-api-3 - 将 Google map 自定义叠加层与主干 View 混合

javascript - 如何使用 CasperJS 检索复选框的值

javascript - 最大高度 : 0 not collapsing Div

android - 可以从后台服务而不是 Activity 打开 GPS 吗?