将地图实例保存在Google地图之外

时间:2015-07-18 02:02:19

标签: html google-maps google-maps-api-3 google-plus google-maps-markers

我制作了一个谷歌地图API(HTML)脚本,当用户点击地图时会创建标记。我还整合了Google+登录功能,因此用户既独特又有个人资料。我现在想要这样做,以便用户可以在他们想要的位置创建他们的标记,然后保存地图,以便他们以后可以回来。但是,我并不希望他们使用这个" https://developers.google.com/maps/documentation/javascript/examples/save-widget"提供功能,因为然后标记与他们的谷歌+同步。换句话说,我只希望标记保存到我的网站,而不是他们的个人谷歌地图。我如何才能在我的网站上保存地图的状态? 继承我代码的小提琴:https://jsfiddle.net/hgvsurt5/ 下面是代码:

<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 个答案:

答案 0 :(得分:3)

您必须以某种方式将所需数据转换为可以发送和存储的格式。一个好的方法是使用Data-layer在地图上绘制要素,您可以轻松使用数据层的toGeoJson方法将数据转换为geoJson并将其发送到服务器(存储数据的地方)。

一个简单的实现:

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>