Skip to content Skip to sidebar Skip to footer

Linking Markers Together Using A Line: Google Maps Api

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

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

Post a Comment for "Linking Markers Together Using A Line: Google Maps Api"