谷歌地图:实时绘制并更新折线

10

我对JS非常菜,很抱歉我没有附上我的代码,因为我所做的一切都是从Google Map文档中的“helloworld”示例中学到的。

问题在于:
我想根据用户当前的位置绘制折线。 所以每一个google.maps.LatLng()应该在此时具有坐标。地图上应该更新整个路径,例如每5秒更新一次。在最后一个点上,就像在地图上进行早晨行走的可视化效果,类似于那样。

我知道如何“绘制”地图并添加点到var flightPlanCoordinates[]中,并请求一些示例或链接,其中我可以找到:

  • 如何将当前位置添加到var flightPlanCoordinates[]
  • 如何以“实时”模式使所有这些内容更新

感谢任何帮助 :)

更新:
尝试做这样的事情,但不起作用


var path = poly.getPath();

var latitude  = position.coords.latitude;
var longitude = position.coords.longitude;

path.push(new google.maps.LatLng(latitude, longitude));

更新 2: 这里有一个很棒的例子,展示了应该如何做:http://kasheftin.github.io/gmaps/


你想要做的是研究HTML5地理位置API - Suvi Vignarajah
尝试这样做,但不起作用:var path = poly.getPath(); var latitude = position.coords.latitude; var longitude = position.coords.longitude; path.push(new google.maps.LatLng(latitude, longitude)); - Rachnog
3个回答

12

您需要使用新路径(已更新为包含新点的路径)更新折线:

// get existing path
var path = poly.getPath();
// add new point
path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
// update the polyline with the updated path
poly.setPath(path);

代码片段: (点击地图以添加点到折线)

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var poly = new google.maps.Polyline({
    map: map,
    path: []
  })
  google.maps.event.addListener(map, 'click', function(evt) {
    // get existing path
    var path = poly.getPath();
    // add new point (use the position from the click event)
    path.push(new google.maps.LatLng(evt.latLng.lat(), evt.latLng.lng()));
    // update the polyline with the updated path
    poly.setPath(path);
  })
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>


2

请尝试以下代码:

var path = poly.getPath().getArray();
path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
poly.setPath(path);

1

目前,该API允许您只需将新的LatLng对象推送到path中即可在地图上进行更新。

正如Complex Polyline示例所示,您可以执行以下操作:

var path = poly.getPath()
path.push(latLng)

其中poly是您的google.maps.Polyline,而latLng是一个google.maps.LatLng


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接