本文介绍了在 Google Maps v3 中绘制两点之间路线的不一致行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景

我正在尝试使用 Google Maps v3 在 n 个点(lat,lan)之间绘制一条路线.为此,我使用 DirectionsService 为我提供路线,然后将该坐标推入 MVCArray,然后使用 绘制该路径折线.

代码

也遇到了同样的问题.

这意味着我可能使用的是过时版本的 Google 地图、未正确初始化或任何其他基本问题或有缺陷的设置.或者在另一方面,它可能是客户端的问题,比如 Mac Chrome 最新版本,因为显然它没有发生在我手机上的 Chrome for Android(Nexus 5,最新,股票)

解决方案

不要将目的地、源和航点位置添加到折线,只添加来自路线服务的点:

var map = null;var infowindow = new google.maps.InfoWindow();var bounds = new google.maps.LatLngBounds();//要连接的点列表var 标记 = [{"title": '杜罗',纬度":'40.480243',"lng": '-3.866172',描述":'1'}, {"title": '雷耶斯卡托利科斯',"lat": '40.47806',"lng": '-3.870937',描述":'2'}, {"title": '瓜达拉马',"lat": '40.478998',"lng": '-3.878755',描述":'3'}];//变量映射;函数初始化(){var mapOptions = {中心:新的 google.maps.LatLng(parseFloat(markers[0].lat),parseFloat(markers[0].lng)),变焦:15,mapTypeId: google.maps.MapTypeId.ROADMAP};var service = new google.maps.DirectionsService();var infoWindow = new google.maps.InfoWindow();map = new google.maps.Map(document.getElementById("map"), mapOptions);var lat_lng = new Array();var 标记 = 新的 google.maps.Marker({位置:map.getCenter(),地图:地图,可拖动:真});bounds.extend(marker.getPosition());google.maps.event.addListener(标记,点击",函数(evt){infowindow.setContent("坐标:" + marker.getPosition().toUrlValue(6));infowindow.open(地图,标记);});for (var i = 0; i 
html,身体,#地图 {宽度:100%;高度:100%;}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></脚本><div id='map'></div>

The scenario

I'm trying to draw a route between n points (lat,lan) using Google Maps v3. To do this I'm using DirectionsService which provides me with a route, then I'm pushing that coordinates into a MVCArray and then drawing that path by using a Polyline.

The code

Here is a jsfiddle demonstrating that part of code here.

HTML:

<div id='map'></div>

CSS:

#map{
    width:400px;
    height:400px;
}

JavaScript:

$(function () {
    //The list of points to be connected
    var markers = [
        {
            "title": 'Duero',
            "lat": '40.480243',
            "lng": '-3.866172',
            "description": '1'
        },
        {
            "title": 'Reyes Catolicos',
            "lat": '40.477997',
            "lng": '-3.870865',
            "description": '2'
        },
        {
            "title": 'Guadarrama',
            "lat": '40.478998',
            "lng": '-3.878755',
            "description": '3'
        }
    ];

    var map;

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

    var infoWindow = new google.maps.InfoWindow();
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    var poly = new google.maps.Polyline({
        map: map,
        strokeColor: '#F3443C'
    });
    var lat_lng = new Array();

    path.push(new google.maps.LatLng(markers[0].lat, markers[0].lng));
    for (var i = 0; i < markers.length; i++) {
        if ((i + 1) < markers.length) {
            var src = new google.maps.LatLng(markers[i].lat, markers[i].lng);
            var des = new google.maps.LatLng(markers[i+1].lat, markers[i+1].lng);

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

Expected behaviour

I should get a set of straight lines drawn, connecting the points (lat,lan) specified in the variable markers, with the specified width and color. More specifically Point 1 being connected just to Point 2 which in turn is connected to Point 3

With the code in the fiddle, I would want to see, this:

Actual behaviour

I get the previous image, but not always. If you refresh, a few times you will end up getting this, which I believe is the result of adding one extra line connecting the points as the crow flies, however, being an inconsistent behaviour I'm struggling to find the source of it, I simplified the example yo have an array of vertices as small as possible, and as far as I can see, the path being drawn should be the same, since the data is the same. Admittedly I've never delved into google maps api in great depth, so the source code is mainly the result of copying and pasting from working online samples, particularly this one which is also suffering from the same issue.

This means that I may be using an outdated version of Google maps, initializing it incorrectly or any other basic problem or flawed setup. Or on the other side of things, it could be a problem with the client, say Mac Chrome latest version, since apparently it's not happening in Chrome for Android on my phone (Nexus 5, latest, stock)

解决方案

Don't add the destination, source and waypoint locations to the polyline, just points from the directions service:

working fiddle

var map = null;
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();

//The list of points to be connected
var markers = [{
  "title": 'Duero',
  "lat": '40.480243',
  "lng": '-3.866172',
  "description": '1'
}, {
  "title": 'Reyes Catolicos',
  "lat": '40.47806',
  "lng": '-3.870937',
  "description": '2'
}, {
  "title": 'Guadarrama',
  "lat": '40.478998',
  "lng": '-3.878755',
  "description": '3'
}];


//    var map;
function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(
      parseFloat(markers[0].lat),
      parseFloat(markers[0].lng)),
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var service = new google.maps.DirectionsService();

  var infoWindow = new google.maps.InfoWindow();
  map = new google.maps.Map(document.getElementById("map"), mapOptions);
  var lat_lng = new Array();

  var marker = new google.maps.Marker({
    position: map.getCenter(),
    map: map,
    draggable: true
  });
  bounds.extend(marker.getPosition());
  google.maps.event.addListener(marker, "click", function(evt) {
    infowindow.setContent("coord:" + marker.getPosition().toUrlValue(6));
    infowindow.open(map, marker);
  });
  for (var i = 0; i < markers.length; i++) {
    if ((i + 1) < markers.length) {
      var src = new google.maps.LatLng(parseFloat(markers[i].lat),
        parseFloat(markers[i].lng));
      createMarker(src);

      var des = new google.maps.LatLng(parseFloat(markers[i + 1].lat),
        parseFloat(markers[i + 1].lng));
      createMarker(des);
      //  poly.setPath(path);
      service.route({
        origin: src,
        destination: des,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
      }, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          var path = new google.maps.MVCArray();
          var poly = new google.maps.Polyline({
            map: map,
            strokeColor: '#F3443C'
          });
          for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
            path.push(result.routes[0].overview_path[i]);
          }
          poly.setPath(path);
          map.fitBounds(bounds);
        }
      });
    }
  }
}

function createMarker(latLng) {
  var marker = new google.maps.Marker({
    position: latLng,
    map: map,
    draggable: true
  });
  bounds.extend(marker.getPosition());
  google.maps.event.addListener(marker, "click", function(evt) {
    infowindow.setContent("coord:" + this.getPosition().toUrlValue(6));
    infowindow.open(map, this);
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  width: 100%;
  height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id='map'></div>

这篇关于在 Google Maps v3 中绘制两点之间路线的不一致行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 14:17