谷歌地图,用户创建标记,如何保存

时间:2015-10-02 13:04:36

标签: javascript google-maps google-maps-api-3 google-maps-markers markers

我已经获得了允许用户在地图上标记标记的代码。我缺少的是如何保存标记,以便在地图重新加载时,标记仍然存在。

<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>

1 个答案:

答案 0 :(得分:1)

您可以将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