如何在客户端上存储谷歌地图地理编码信息?

时间:2013-11-16 21:24:10

标签: javascript google-maps google-maps-api-3

我希望用户执行以下操作: 1)输入他们的街道地址和邮政编码并点击“提交”,这将触发谷歌地图对地址进行地理编码并在地图上放置标记。我正在使用下面的代码(这是正常工作并获取我需要的所有地址信息):

var geocoder;
var map;

function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(37.7789, -122.3917);
    var mapOptions = {
        center: latlng,
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}

function codeAddress() {
  var address = document.getElementById('streetAddress').value +", "+document.getElementById('zipCode').value;
  geocoder.geocode( { 'address': address, 'region': 'US'}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        if (results[0].address_components) {
            for (var i in results[0].address_components) {
                if (typeof(results[0].address_components[i]) === "object" && results[0].address_components[i].types[0] == "street_number") {
                    var streetNumber= results[0].address_components[i].long_name;
                } else if (typeof(results[0].address_components[i]) === "object" && results[0].address_components[i].types[0] == "route") {
                    var streetName= results[0].address_components[i].short_name;
                } else if (typeof(results[0].address_components[i]) === "object" && results[0].address_components[i].types[0] == "neighborhood") {
                    var neighborhood= results[0].address_components[i].short_name;
                } else if (typeof(results[0].address_components[i]) === "object" && results[0].address_components[i].types[0] == "administrative_area_level_1") {
                    var state= results[0].address_components[i].short_name;
                } else if (typeof(results[0].address_components[i]) === "object" && results[0].address_components[i].types[0] == "postal_code") {
                    var zipCode= results[0].address_components[i].long_name;
                }   
            }
        }
        console.log(streetNumber+", "+streetName+", "+neighborhood+", "+state+", "+zipCode);        
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}   

google.maps.event.addDomListener(window, 'load', initialize);

2)用户看到标记后,我希望他们点击“确认”按钮将此数据提交给我的服务器(我通过他们的Javascript API使用Firebase)。我的问题是如何在Google Maps返回数据的时间和用户点击时间之间最好地存储变量'streetNumber','streetName','city','state','zipCode'和'neighborhood' “确认”按钮?我唯一能想到的就是将它存储在浏览器窗口中(例如window.streetName,window.streetNumber等),但我知道这不是最佳实践。

1 个答案:

答案 0 :(得分:0)

你可以,例如将这些数据存储为按钮的属性,以后可以很容易地访问它们(但它也不是一个好习惯)。

您可以做的最好的事情是将所有对象存储在一个"类" ( all 我指的是全局的所有内容,目前mapgeocodercodeAddressinitialize都是全局的

这是一个示例代码(可以使用,它不会公开任何全局属性):

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">
</script>
<script  type="text/javascript">
//a self-executing, anonymous function
(function(opts,ns){

  //"that" is our object, it holds all properties and methods
  //and is only visible within the scope of this function
  var that = {geocoder:  null,
              map:       null,
              opts:      opts,
              ns:        ns,
              postData:  null},
      goo  =  google.maps,
      byId = function(id){return document.getElementById(id);};

  //initialize the map
  that.initialize=function() {
    var latlng = new goo.LatLng(this.opts.lat,this.opts.lng);
    var mapOptions = {
        center:     latlng,
        zoom:       12,
        mapTypeId:  google.maps.MapTypeId.ROADMAP
    };
    this.map = new goo.Map(byId(this.opts.ids.map), mapOptions);
    //assign click-handlers to the buttons
    goo.event.addDomListener(byId(this.opts.ids.btnGeo),'click',function(){
                                              that.codeAddress.call(that);});
    goo.event.addDomListener(byId(this.opts.ids.btnSend),'click',function(){
                                              that.onSubmit.call(that);});

  }
  //send the data here  
  that.onSubmit=function(){
    alert(JSON.stringify(that.postData));
  }
  //parse the address-components into an object
  that.parseAddressComponents=function(ac){
    var components={
                    street_number:              ['streetNumber', 'long_name'],
                    route:                      ['streetName', 'short_name'],
                    administrative_area_level_1:['state', 'short_name'],
                    neighborhood:               ['neighborhood', 'short_name'],
                    postal_code:                ['zipCode', 'long_name']
                   },o={};

    for(var i=0;i<ac.length;++i){
      inner:for(var c in components){
        if(ac[i].types[0]==c){
          o[components[c][0]]=ac[i][components[c][1]];
          break inner;
        }
      }
    }
    return o;
  }

  //geocoding-callback
  that.geoCallback=function(results, status){
      if (status == goo.GeocoderStatus.OK) {
       //store the parsed address-components as property of "that"
       that.postData=that.parseAddressComponents(results[0].address_components);

        that.map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: that.map,
            position: results[0].geometry.location
      });
    } else {
      that.postData={};
      alert(status);
    }
  }
  //geocoding
  that.codeAddress=function() {
    var address = [byId(this.opts.ids.uiAddr).value,
                   byId(this.opts.ids.uiZip).value].join(',');
    //initialize geocoder on first run
    if(!this.geocoder){this.geocoder=new goo.Geocoder();}
      this.geocoder.geocode( { 'address': address, 'region': this.opts.region}, 
                              this.geoCallback);
  }
  //make "that" global when needed
  if(ns)window[ns]=that;
  //load-handler
  goo.event.addDomListener(window, 'load',function(){
                    that.initialize();});
})
(   //some properties for the object
    {
      lat:37.7789,
      lng:-122.3917,
      region:'US',
      ids:{ map     :'map_canvas',
            btnGeo  :'geobutton',
            btnSend :'sendbutton',
            uiAddr  :'streetAddress',
            uiZip   :'zipCode'}
    },
    //supply a name for the object here when you want to make it global
    null
);
/*]]>*/
</script>
<fieldset>
  streetAddress:<input id="streetAddress" value="paisley park">
  zipCode:<input id="zipCode" value="55422">
  <input id="geobutton" type="button" value="geocode">
  <input id="sendbutton" type="button" value="send">
</fieldset>
<div id="map_canvas" style="height:300px;"></div>