在我的应用程序中,我想在路径中的每个latLng上存储应用程序定义的数据。 我已经使用下面的代码示例来实现这一点,但我想知道这是否是一个没有文档的侥幸,只是“碰巧”工作并且可能在将来被破坏,或者它是否应该始终有效的完全有效的代码? 简而言之,'getPath'保证返回传入的相同latLng对象,或者它可以传回具有相同lat和相同lng的新对象,但google不关心的任何其他东西可能仍然存在吗?
感谢您的帮助
点击该行,它应警告“一二三”。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.0, -1.5),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var polyline = new google.maps.Polyline({
map: map,
strokeColor: "blue",
strokeThicknedss: 2
});
polyline.setPath([
getLatLng(51.9, -1.4, "one"),
getLatLng(52.0, -1.5, "two"),
getLatLng(52.0, -1.6, "three")
]);
google.maps.event.addListener(polyline, "click", function() {
var path = this.getPath().getArray();
var datas = [];
for(var i = 0; i < path.length; i++) {
var ll = path[i];
datas.push(ll.data);
}
alert(datas.join("\n"));
});
}
function getLatLng(lat, lng, data) {
var ll = new google.maps.LatLng(lat, lng);
ll.data = data;
return ll;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
答案 0 :(得分:0)
好according to the docs getPath()'检索第一条路径'。你只需要使用setPath()设置路径......我不确定谷歌是否会破坏这些数据;你的方法对我来说似乎很合理。
答案 1 :(得分:0)
我发现存储折线的最佳方法是在几何库中使用Google的编码功能。
var polylineToStore = google.maps.geometry.encoding.encodePath(polyline.getPath());
这会将polylineToStore变量设置为字符串。如果要重复使用该编码折线,只需对其进行解码:
polyline.setPath(google.maps.geometry.encoding.decodePath(polylineToStore))
https://developers.google.com/maps/documentation/javascript/geometry#Encoding