gpt4 book ai didi

javascript - Google map ,用户创建标记,如何保存

转载 作者:行者123 更新时间:2023-12-03 08:45:28 32 4
gpt4 key购买 nike

我有代码允许用户在 map 上固定标记。我缺少的是如何保存标记,以便本地图重新加载时,标记仍然存在。

<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var map;
var myCenter=new google.maps.LatLng(38.9047,-77.0164);

function initialize()
{
var mapProp = {
center:myCenter,
zoom:7,
mapTypeId:google.maps.MapTypeId.ROADMAP
};

map = new google.maps.Map(document.getElementById("googleMap"),mapProp);

google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}

function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map,marker);
}

google.maps.event.addDomListener(window, 'load', initialize);

</script>

最佳答案

您可以利用google.maps.Data API为此,下面的示例演示了如何通过 localStorage 保存和加载标记信息.

function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map, marker);

//place marker info
map.data.add(new google.maps.Data.Feature({properties:{},geometry:new google.maps.Data.Point(location)}));
}



function saveMarker() {
map.data.toGeoJson(function (json) {
localStorage.setItem('geoData', JSON.stringify(json));
});
}


function clearMarkers() {
map.data.forEach(function (f) {
map.data.remove(f);
});
}

function loadMarkers(map) {
var data = JSON.parse(localStorage.getItem('geoData'));
map.data.addGeoJson(data);
}

<强> Demo

关于javascript - Google map ,用户创建标记,如何保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32907831/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com