linking markers together using a line: google maps api

左心房为你撑大大i 提交于 2019-12-25 18:55:43

问题


I am looking to code a feature that when a user clicks a marker appears then when the user clicks for the next marker it will connect it to the previous marker using a line. I have tried using the google api documentation for this but cannot seem to get the feature to work. can anyone help?

Here is the code:

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

回答1:


Simplest thing is to make the polyline global, then do everything inside the addLatLng event handler function:

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

code snippet:

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


来源:https://stackoverflow.com/questions/34655257/linking-markers-together-using-a-line-google-maps-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!