【发布时间】:2016-05-19 03:49:51
【问题描述】:
是否可以在 Google 地图中仅选择折线的一部分?我有用户添加的标记,并且在标记之间绘制了一条折线。两个标记之间的折线代表两个地方之间的路线。我希望用户能够单击折线,该部分会改变颜色,然后插入另一个点。我还想获取折线连接的标记的标记 ID(在添加标记时设置)。
这是我的代码所基于的谷歌示例代码,因为我的代码非常混乱,所以我将其发布。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex Polylines</title>
<style>
html, body
{
height: 100%;
margin: 0;
padding: 0;
}
#map
{
height: 100%;
}
</style>
</head>
<body>
<div id="map">
</div>
<script>
var poly;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: { lat: 41.879, lng: -87.624} // Center the map on Chicago, USA.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
// Add a listener for the click event
map.addListener('click', addLatLng);
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap"></script>
</body>
</html>
到目前为止,我只设法为整个折线添加了一个点击事件侦听器:
google.maps.event.addListener(poly, 'click', function() {
poly.setOptions({strokeColor: '#76EE00'});
});
【问题讨论】:
-
我认为SO-6170176 可能会有所帮助。
-
@gerardnimo 谢谢,我确实看过那个问题,但我仍然不知道如何将它应用于我的问题。
标签: javascript jquery google-maps google-maps-api-3