问题
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