0

Я создал скрипт API Google Maps (HTML), который создал маркеры, когда пользователь нажимает на карту. Я также интегрировал функции входа в систему Google+, поэтому пользователи уникальны и имеют профили. Теперь я хочу сделать так, чтобы пользователи могли создавать свои маркеры на своих желаемых позициях, а затем сохранять карту, чтобы они могли вернуться к ней позже. Однако я не хочу, чтобы они использовали эту функцию «https://developers.google.com/maps/documentation/javascript/examples/save-widget», потому что маркеры синхронизируются с их Google +. Другими словами, я хочу, чтобы маркеры сохранялись на моем веб-сайте, а не на своих личных картах Google. Как я могу сохранить состояние карты только на моем сайте? Heres скрипка моего кода: https://jsfiddle.net/hgvsurt5/ Heres код:Сохранить экземпляр карты за пределами Google Maps

<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

Вы должны каким-то образом принести желаемые данные в формат, который может быть отослано и хранится. Хорошим подходом было бы использовать Data-layer для рисования функций на карте, вы можете легко использовать метод toGeoJson уровня данных для преобразования данных в геозон и отправить его на сервер (где вы храните данные).

Простая реализация:

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>

Смежные вопросы