Save Map Instance outside of Google Maps

2019-02-11 07:08发布

I've made a google maps API (HTML) script that created markers when the user clicks on the map. I've also integrated Google+ login functions so users are unique and have profiles. I now want to make it so users can create their markers on their desired positions and then save the map so they can come back to it later. I however don't want them to use this "https://developers.google.com/maps/documentation/javascript/examples/save-widget" provided function because then the markers are synched to their google+. In other words I only want the markers to save to my website, not to their personal google maps. How would I go about saving the state of the map only on my site? Heres the fiddle of my code: https://jsfiddle.net/hgvsurt5/ Heres the code:

<head>
    <style>
        #map-canvas {
            width: 900px;
            height: 600px;
        }
        .controls {
            margin-top: 16px;
            border: 1px solid transparent;
            border-radius: 2px 0 0 2px;
            box-sizing: border-box;
            -moz-box-sizing: border-box;
            height: 32px;
            outline: none;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        }
        #pac-input {
            background-color: #fff;
            font-family: Roboto;
            font-size: 15px;
            font-weight: 300;
            margin-left: 12px;
            padding: 0 11px 0 13px;
            text-overflow: ellipsis;
            width: 400px;
        }
        #pac-input:focus {
            border-color: #4d90fe;
        }
        .pac-container {
            font-family: Roboto;
        }
        #type-selector {
            color: #fff;
            background-color: #4d90fe;
            padding: 5px 11px 0px 11px;
        }
        #type-selector label {
            font-family: Roboto;
            font-size: 13px;
            font-weight: 300;
        }
    </style>
    <title>Places search box</title>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
    <script>
        // This example adds a search box to a map, using the Google Place Autocomplete
        // feature. People can enter geographical searches. The search box will return a
        // pick list containing a mix of places and predicted search terms.

        function initialize() {
            var marker = []
            var map = new google.maps.Map(document.getElementById('map-canvas'), {
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            var defaultBounds = new google.maps.LatLngBounds(
            new google.maps.LatLng(-33.8902, 151.1759),
            new google.maps.LatLng(-33.8474, 151.2631));
            map.fitBounds(defaultBounds);

            // Create the search box and link it to the UI element.
            var input = /** @type {HTMLInputElement} */
            (
            document.getElementById('pac-input'));
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

            var searchBox = new google.maps.places.SearchBox(
            /** @type {HTMLInputElement} */
            (input));

            // [START region_getplaces]
            // Listen for the event fired when the user selects an item from the
            // pick list. Retrieve the matching places for that item.
            google.maps.event.addListener(searchBox, 'places_changed', function() {
                var places = searchBox.getPlaces();

                if (places.length == 0) {
                    return;
                }
    </script>
    <script>
        var map;
        var myCenter = new google.maps.LatLng(51.508742, -0.120850);

        function initialize() {
            var mapProp = {
                center: myCenter,
                zoom: 5,
                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,
                draggable: true,
            });
            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>
</head>

<body>
    <div id="googleMap" style="width:900px;height:600px;"></div>
</body>

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-11 07:42

You must somehow bring the desired data into a format which may be sended and stored. A good approach would be to use a Data-layer to draw the features on the map, you may easily use the method toGeoJson of the Data-layer to convert the data into a geoJson and send it to a server(where you store the data).

A simple implementation:

function initialize() {
  var map = new google.maps.Map(document.getElementById("googleMap"), {
      center: new google.maps.LatLng(51.508742, -0.120850),
      zoom: 5,
      noClear: true
    }),
    //this may be the stored data
    data = {
      "type": "FeatureCollection",
      "features": [{
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [-0.120850, 51.508742]
        },
        "properties": {}
      }]
    },
    win = new google.maps.InfoWindow,
  
      
    //some buttons for interaction
    ctrl = document.getElementById('datactrl'),


    fx = {
      'data-save': {
        click: function() {
          //use this method to store the data somewhere,
          //e.g. send it to a server
          map.data.toGeoJson(function(json) {
            data = json;
          });

        }
      },
      'data-show': {
        click: function() {

          alert('you may send this JSON-string to a server and store it there:\n\n' +
            JSON.stringify(data))
        }
      },
      'data-load': {
        click: function() {
          //use this method to load the data from somwhere
          //e.g. from a server via loadGeoJson

          map.data.forEach(function(f) {
            map.data.remove(f);
          });
          map.data.addGeoJson(data)
        },
        init: true
      },
      'data-clear': {
        click: function() {
          //use this method to clear the data
          //when you also want to remove the data on the server 
          //send a geoJSON with empty features-array to the server

          map.data.forEach(function(f) {
            map.data.remove(f);
          });
          data = {
            type: "FeatureCollection",
            features: []
          };


        }
      }
    };


  for (var id in fx) {
    var o = ctrl.querySelector('input[id=' + id + ']');
    google.maps.event.addDomListener(o, 'click', fx[id].click);
    if (fx[id].init) {
      google.maps.event.trigger(o, 'click');
    }
  }




  map.controls[google.maps.ControlPosition.TOP_CENTER].push(ctrl);


  

  function placeMarker(location) {
    var feature = new google.maps.Data.Feature({
      geometry: location
    });
    map.data.add(feature);
  }
  google.maps.event.addListener(map, 'click', function(event) {
    placeMarker(event.latLng);
  });


  google.maps.event.addListener(map.data, 'click', function(e) {
    if (e.feature.getGeometry().getType() === 'Point') {

      win.setOptions({
        content: 'Latitude: ' + e.feature.getGeometry().get().lat() +
          '<br>Longitude: ' + e.feature.getGeometry().get().lng(),
        pixelOffset: new google.maps.Size(0, -40),
        map: map,
        position: e.feature.getGeometry().get()
      });
    }
  });
}



google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#googleMap {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="googleMap">
  <div id="datactrl">
    <input type="button" id="data-save" value="save" />
    <input type="button" id="data-show" value="show saved data" />
    <input type="button" id="data-load" value="load saved data" />
    <input type="button" id="data-clear" value="remove all data" />
  </div>
</div>

查看更多
登录 后发表回答