所以我有一个需要多个位置/标记的谷歌地图。 到目前为止,我只是将它们设置为像这样的数组
var locations = [
['Sheffield', 53.381690, -0.277405, 3],
['Barnsley', 53.824976, -0.832214, 2],
['Leeds', 53.865486, -1.216736, 1]
];
我需要做的是从div中的单个attr标签中取出它们,地图代码看起来像这样。
<div id="map">
<div class="marker" postcode="S71 1ET" data-lat="53.381690" data-lng="-0.277405"></div>
<div class="marker" postcode="M16 0RA" data-lat="53.824976" data-lng="-0.832214"></div>
<div class="marker" postcode="S2 4SU" data-lat="53.865486" data-lng="-1.216736"></div>
</div>
理想情况下,我还希望通过邮政编码attr来填充位置,而不是在lat lng之外。那么它需要使用Geocode吗?
任何帮助都会很好,到目前为止我的所有代码都在下面。
<div id="map">
<div class="marker" postcode="S71 1ET" data-lat="53.381690" data-lng="-0.277405"></div>
<div class="marker" postcode="M16 0RA" data-lat="53.824976" data-lng="-0.832214"></div>
<div class="marker" postcode="S2 4SU" data-lat="53.865486" data-lng="-1.216736"></div>
</div>
<script>
var locations = [
['Sheffield', 53.381690, -0.277405, 3],
['Barnsley', 53.824976, -0.832214, 2],
['Leeds', 53.865486, -1.216736, 1]
];
function initMap() {
var myLatLng = {lat: 53.774689, lng: 5.888672};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: myLatLng
});
var count;
for (count = 0; count < locations.length; count++) {
new google.maps.Marker({
position: new google.maps.LatLng(locations[count][1], locations[count][2]),
map: map,
title: locations[count][0]
});
}
}
</script>
答案 0 :(得分:0)
理想情况下,我也希望通过邮政编码attr填充位置,而不是关闭lat lng
我倾向于不同意。如果您有lat和lng,请使用它们。此外,你确实需要地理编码,地址搜索,......这会减慢一切,这是更多的代码,这对于不同国家/地区的人们来说可能会获得不同国家/地区的相同邮政编码......
无论如何,这有效:
<style>#map {height: 400px;}</style>
<div id="map"></div>
<div id="markers">
<div class="marker" data-postcode="S71 1ET" data-lat="53.381690" data-lng="-0.277405"></div>
<div class="marker" data-postcode="M16 0RA" data-lat="53.824976" data-lng="-0.832214"></div>
<div class="marker" data-postcode="S2 4SU" data-lat="53.865486" data-lng="-1.216736"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<script>
// notice, jQuery makes it easier to read/write from/to HTML elements. But it's not required.
function readMarkersData() {
var locations = [];
var markerdivs = document.getElementById('markers').children;
for(var i=0; i<markerdivs.length; i++) {
var item = markerdivs[i];
locations.push([
item.getAttribute('data-postcode'),
item.getAttribute('data-lat'),
item.getAttribute('data-lng')
])
}
return locations;
}
function initMap() {
var myLatLng = {lat: 53.774689, lng: 5.888672};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: myLatLng
});
var count;
var locations = readMarkersData();
for (count = 0; count < locations.length; count++) {
new google.maps.Marker({
position: new google.maps.LatLng(locations[count][1], locations[count][2]),
map: map,
title: locations[count][0]
});
}
}
</script>