将地图实例保存在Google地图之外 [英] Save Map Instance outside of Google Maps

查看:80
本文介绍了将地图实例保存在Google地图之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了Google地图API(HTML)脚本,用于在用户点击地图时创建标记。我还集成了Google+登录功能,以便用户具有独特性并拥有个人资料。我现在想做的是让用户可以在他们想要的位置创建标记,然后保存地图,以便稍后再回来。不过,我不希望他们使用此 https://开发人员。 google.com/maps/documentation/javascript/examples/save-widget 提供的功能,因为这些标记与Google +同步。换句话说,我只想将标记保存到我的网站,而不是保存到他们的个人谷歌地图。我将如何去保存只在我的网站上的地图状态?
我的代码小提琴: https://jsfiddle.net/hgvsurt5/
代码:


 <头> 
< style>
#map-canvas {
width:900px;
height:600px;
}
.controls {
margin-top:16px;
border:1px透明;
border-radius:2px 0 0 2px;
box-sizing:border-box;
-moz-box-sizing:border-box;
height:32px;
概述:无;
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;
文本溢出:省略号;
width:400px;
}
#pac-input:focus {
border-color:#4d90fe;
}
.pac-container {
font-family:Roboto;
}
#type-selector {
color:#fff;
背景颜色:#4d90fe;
padding:5px 11px 0px 11px;
}
#type-selector label {
font-family:Roboto;
font-size:13px;
font-weight:300;
}
< / style>
< title>位置搜寻框< / title>
< script src =https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places>< / script>
< script>
//此示例使用Google Place自动完成
//功能将搜索框添加到地图。人们可以输入地理搜索。搜索框将返回一个
//选择列表,其中包含地点和预测搜索条件的混合。

函数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),
google.maps.LatLng(-33.8474,151.2631 ));
map.fitBounds(defaultBounds);

//创建搜索框并将其链接到UI元素。
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]
//监听用户从
//选择列表中选择一个项目时触发的事件。检索该项目的匹配地点。
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);

函数initialize(){
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId :google.maps.MapTypeId.ROADMAP
;
$ b $ map = new google.maps.Map(document.getElementById(googleMap),mapProp);

google.maps.event.addListener(map,'click',function(event){
placeMarker(event.latLng);
});
}

函数placeMarker(location){
var marker = new google.maps.M arker({
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 =googleMapstyle =width:900px; height:600px;>< / div>
< / body>


解决方案

您必须以某种方式将所需数据转换为可能被发送和存储的格式。一种好的方法是使用 数据 -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}),//这可能是存储的数据data = {type:FeatureCollection,features:[{type:Feature,geometry:{type:点,坐标:[-0.120850,51.508742]},正确关系:{}}]},win = new google.maps.InfoWindow,//用于交互的一些按钮ctrl = document.getElementById('datactrl'),fx = {'data-save':{click:function() {//使用此方法将数据存储在某处,//例如将它发送到服务器map.data.toGeoJson(function(json){data = json;}); }},'data-show':{click:function(){alert('你可以发送这个JSON字符串到服务器并存储它:\\\
\\\
'+ JSON.stringify(data))} },'data-load':{click:function(){//使用此方法从somwhere加载数据//例如从服务器通过loadGeoJson map.data.forEach(function(f){map.data.remove(f);}); map.data.addGeoJson(data)},init:true},'data-clear':{click:function(){//使用此方法清除数据//当您还想删除服务器上的数据时//发送一个geoJSON和空的features-array到服务器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);函数placeMarker(location){var feature = new google.maps.Data.Feature({geometry:location}); map.data.add(特征); } 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 %;保证金:0; padding:0;}

< script src =https ://maps.googleapis.com/maps/api/js?v=3>< / script>< div id =googleMap> < div id =datactrl> < input type =buttonid =data-savevalue =save/> < input type =buttonid =data-showvalue =show saved data/> < input type =buttonid =data-loadvalue =load saved data/> < input type =buttonid =data-clearvalue =删除所有数据/> < / div>< / div>

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>

解决方案

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>

这篇关于将地图实例保存在Google地图之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆