使用Google Maps API绘制地图路径/航点并播放路线 [英] Plot a map path / waypoints using the Google Maps API and play the route

查看:143
本文介绍了使用Google Maps API绘制地图路径/航点并播放路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当地图加载时,我想要绘制的点数A,B,C,D,E,然后F连接一个接一个。

我已成功绘制点,但无法动态链接点



这是我的代码:

 <脚本类型= 文本/ JavaScript的 > 
var marker = [{
title:'Alibaug',
lat:'12 .97721863',
lng:'80 .22206879',
描述:'Alibaug是印度马哈拉施特拉邦Konkan地区Raigad区的一个沿海城市和市议会。'
},{
title:'孟买',
拉美:'12 .9962529',
lng:'80 .2570098',
描述:'孟买以前是孟买,是印度马哈拉施特拉邦的首府城市'
}, {
title:'Pune',
lat:'12 .97722816',
lng:'80 .22219086',
description:'浦那是第七印度最大的大都市,孟买之后在马哈拉施特拉邦的第二大城市,'
}];
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地图搜索**************** //
//创建搜索框并将其链接到UI元素。
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));
//监听用户从
//选择列表中选择一个项目时触发的事件。检索该项目的匹配地点。
google.maps.event.addListener(searchBox,'places_changed',function(){
var places = searchBox.getPlaces();

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

//对于每个地方,获取图标,地名和位置
markers = [];
var bounds = new google.maps.LatLngBounds();
var place = null;
var viewport = null;
为(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)
};

//为每个地方创建一个标记
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());
});
//将SearchBox结果偏移到位于
//当前地图视口范围内的地方。
google.maps.event.addListener(map,'bounds_changed',function(){
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
// *********** Google地图搜索结束**************** //


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);

// ***********路由**************** //

//初始化路径数组
var path = new google.maps.MVCArray();

//初始化定向服务
var service = new google.maps.DirectionsService();

//设置路径笔触颜色
var poly = new google.maps.Polyline({
map:map,
strokeColor:'#4986E7'
});

//循环和绘制路径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]);
}
}
});



$ b function handleLocationError(browserHasGeolocation,infoWindow,pos){
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation?
'错误:Geolocation服务失败。':
'错误:您的浏览器不支持地理定位。



输出将类似于:



如何回放显示沿着此路线的点?有没有任何工作的例子?

解决方案

https://duncan99.wordpress.com/2015/01/22/animated-paths-with-google-maps/ 解释如何动画路线。

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



 <!DOCTYPE html>< html lang =en>< head> < meta charset =UTF-8> < title>地图示例< / title>< / head>< body> < button id =animate>重做动画< / button> < div id =map_canvasstyle =width:600px; height:600px>< / div> < script type =text / javascript> var markers = [{title:'Alibaug','lat':'18 .6581725','lng':'72 .8637616','description':'Alibaug是Konkan地区Raigad区的一个沿海城市和市议会马哈拉施特拉邦,印度。'},{title:'孟买','lat':'19 .0458547','lng':'72 .9434202','描述':'孟买以前是孟买,是印度的首都城邦马哈拉施特拉邦。'},{title:'Pune','lat':'18.5247663','lng':'73.7929273','description':'Pune是印度第七大都市,第二大孟买之后的马哈拉施特拉邦。'}];函数animatePath(map,route,marker,pathCoords){var index = 0; route.setPath([]); (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();对于(i = 0; i  

I am trying to plot the visited path as a mapped route is played through, as in the following example:

When a map is loaded I want the plotted points A, B, C, D, E, and then F to connect one after another.

I have successfully plotted the points, but I cannot dynamically link the points one after another.

This is my code:

<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.');
}

Output will be similar to:

How can I play back showing the points along this mapped route? Is there any working example?

解决方案

There is a good blog post with example code at https://duncan99.wordpress.com/2015/01/22/animated-paths-with-google-maps/ explaining how to animate a route.

The difference between that example and your question is that you have way points in your route. You can either fetch the whole route at once with way points, or fetch the route as you were doing in your code above. I have included a coded snippet below which uses way points (max of 8 available with free version of google maps). If you use the method in your code, you need to make sure that the entire path has loaded before you start the animation.

<!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>

这篇关于使用Google Maps API绘制地图路径/航点并播放路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆