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

Google maps: Live drawing and updating a Polyline

本文关键字:更新 折线 绘制 实时 谷歌地图      更新时间:2023-09-26

我真的是JS的新手,很抱歉,我没有附加我的代码,因为我所做的一切 - 来自Google Map Docs的"helloworld"示例。

那么,有什么问题: 我想根据用户的当前位置绘制一条折线。因此,每个google.maps.LatLng()目前都应该有坐标。在地图上应该出现整个更新方式,例如,每 5 秒更新一次。最后,它就像在地图上行走的早晨的可视化,类似的东西。

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

  • 如何将当前位置添加到变量飞行计划坐标[]
  • 如何使所有这些东西在"实时"模式下更新

感谢您的任何帮助:)

上级:

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

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

UPD2:这是一个很酷的例子,应该如何 http://kasheftin.github.io/gmaps/

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

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

尝试以下代码:

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

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

如他们的复杂折线示例所示,您可以执行以下操作:

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

poly是您google.maps.Polyline的地方,latLng google.maps.LatLng.