我使用ContextMenu作爲其他目的的東西,但這個想法似乎很好,用谷歌地圖上的點之間的距離來標記多段線。ContextMenu.js標籤顯示所有菜單項的最後一個條目的標籤
我希望標籤在每次將鼠標懸停在顯示該腿的距離的折線上時顯示。我確定距離沒有問題,但是,標籤總是顯示最後一次輸入的距離,而不是確定該距離的距離。
我創建了一個多段線的數組,以便每個人都可以顯示點之間的距離,它似乎工作得很好,除了距離標籤。
這是我試圖實現的減少版本。
var flightPath = [];
var distanceLables = [];
var map;
function initMap() {
//Google Map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 0,
lng: -180
},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
//waypoints for the Polyline
var flightPlanCoordinates = [{
lat: 37.772,
lng: -122.214
}, {
lat: 21.291,
lng: -157.821
}, {
lat: -18.142,
lng: 178.431
}, {
lat: -27.467,
lng: 153.027
}];
//drawing each leg of the PolyLine indiviually so that mouseover/mouseout events can be customised to each leg
for (i = 0; i < flightPlanCoordinates.length - 1; i++) {
var tempCoords = [];
tempCoords.push(flightPlanCoordinates[i]);
tempCoords.push(flightPlanCoordinates[i + 1]);
flightPath.push(new google.maps.Polyline({
path: tempCoords,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
}));
//Creating the Context Menu which is just one line with the leg number
var contextMenuOptions = {};
contextMenuOptions.classNames = {
menu: 'context_menu displance_display',
menuSeparator: 'context_menu_separator'
};
var menuItems = [];
menuItems.push({
className: 'context_menu_item',
eventName: 'distance_click',
id: 'distanceItem',
label: 'Leg #' + i
}); //Label should represent the leg
contextMenuOptions.menuItems = menuItems;
var pos = distanceLables.push(new ContextMenu(map, contextMenuOptions)) - 1;
//mouseover/mouseout events to show and hide the label
google.maps.event.addListener(flightPath[i], 'mouseover', function(mouseEvent) {
distanceLables[pos].show(mouseEvent.latLng);
});
google.maps.event.addListener(flightPath[i], 'mouseout', function(mouseEvent) {
distanceLables[pos].hide();
});
}
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.context_menu {
background-color: #ffff90;
border: 1px solid gray;
}
.context_menu_item {
padding: 3px 6px;
background-color: #ffff90;
}
.context_menu_item:hover {
background-color: #4b545f;
color: #fff;
}
.context_menu_separator {
background-color: gray;
height: 1px;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Problem</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type='text/javascript' src='http://maps.googleapis.com/maps/api/js?ver=4.2.2'></script>
<script src="http://code.martinpearman.co.uk/googlemapsapi/contextmenu/1.0/src/ContextMenu.js"></script>
</head>
<body onload="initMap()">
<div id="map"></div>
</body>
</html>
感謝,
斯圖
請提供一個[最小,完整,已測試和可讀的示例](http://stackoverflow.com/help/mcve)來說明問題。 – geocodezip
謝謝@geocodezip,我現在已將片段更改爲一個工作示例。 –