简体   繁体   中英

Google Map, Users Create Markers, How do I save

I've got code to allow users to pin a marker on a map. What I am missing is how to save the markers so that when the map reloads, the markers are still there.

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

You could utilize google.maps.Data API for that purpose, the example below demonstrates how to save and load markers info via 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM