使用一行将标记链接在一起:googlemapsapi

linking markers together using a line: google maps api

本文关键字:链接 在一起 googlemapsapi 一行      更新时间:2023-09-26

我想编写一个功能代码,当用户单击一个标记时,它会出现,然后当用户单击下一个标记,它会使用一行将其连接到上一个标记。我已经尝试过使用谷歌api文档来实现这一点,但似乎无法使该功能发挥作用。有人能帮忙吗?

这是代码:

google.maps.event.addListener(map, "click", function(event) {
var marker = new google.maps.Marker({
      position: event.latLng,
      map: map
    });
    poly = new google.maps.Polyline({
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 3
  });
    poly.setMap(map);
    map.addListener('click', addLatLng);
  }
  function addLatLng(event) {
  var path = poly.getPath();
  path.push(event.latLng);
  var marker = new google.maps.Marker({
  position: event.latLng,
  title: '#' + path.getLength(),
  );

最简单的事情是使折线全局化,然后在addLatLng事件处理程序函数中执行所有操作:

// global polyline
var map;
var poly = new google.maps.Polyline({
  strokeColor: '#000000',
  strokeOpacity: 1.0,
  strokeWeight: 3
});
// add marker and point to polyline path
function addLatLng(event) {
  var path = poly.getPath();
  path.push(event.latLng);
  var marker = new google.maps.Marker({
    position: event.latLng,
    title: '#' + path.getLength(),
    map: map
  });
};

代码片段:

// global variables
var map;
var poly = new google.maps.Polyline({
  strokeColor: '#000000',
  strokeOpacity: 1.0,
  strokeWeight: 3
});
function initialize() {
  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
    });
  map.addListener('click', addLatLng);
  // add the polyline to the map
  poly.setMap(map);
}
function addLatLng(event) {
  var path = poly.getPath();
  path.push(event.latLng);
  var marker = new google.maps.Marker({
    position: event.latLng,
    title: '#' + path.getLength(),
    map: map
  });
};
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"></script>
<div id="map_canvas"></div>