【问题标题】:How do I use Google Maps geocoder.getLatLng() and store its result in a database?如何使用 Google Maps geocoder.getLatLng() 并将其结果存储在数据库中?
【发布时间】:2011-08-12 13:28:44
【问题描述】:

大家好!我尝试使用 getLatLng() 对邮政/邮政编码列表进行地理编码,并将生成的点存储在数据库中,以便稍后放置在地图上。这是我到目前为止所得到的:

 $(".geocodethis").click(function () {
    var geocoder = new GClientGeocoder();
    var postalCode = $(this).siblings(".postal").val();
    var id = $(this).siblings(".id").val();

    geocoder.getLatLng(postalCode, function (point) {
        if (!point) {
            alert(postalCode + " not found");
        } else {
            alert(point);
            var serializedPoint = $.param(point);                
            //Geocode(id, point);
        }
    });

});

function Geocode(id, point) {
    alert(point);
    $.post("/Demographic/Geocode/" + id, point, function () {
        alert("success?");
    });
}

但是当我尝试序列化点对象或在$.post() 中使用它时,我的错误控制台中出现了this.lat is not a function

根据我的研究,我了解到geocoder.getLatLng() 是异步的,这会如何影响我正在尝试做的事情?我没有在循环中运行这段代码,我正在尝试使用匿名回调函数发布这一点。

如何保存point 中的信息以供日后使用?

更新

创建标记并尝试发布仍会导致错误控制台中出现this.lat is not a function

$(".geocodethis").click(function () {
        var geocoder = new GClientGeocoder();
        var postalCode = $(this).siblings(".postal").val();
        var id = $(this).siblings(".id").val();

        geocoder.getLatLng(postalCode, function (point) {
            if (!point) {
                alert(postalCode + " not found");
            } else {
                alert(point);
                var marker = new GMarker(point);

                $.post("/Demographic/Geocode/" + id, marker, function () {
                    alert("success?");
                });
            }
        });

    });

** 另一个更新 **

我确实需要保存地理编码地址以备后用,即使我将纬度/经度值存储在数据库中并在准备将其放到地图上时重新制作标记。同样,序列化或发布 - 似乎以谷歌地图功能以外的任何方式使用该点会在我的错误日志中给出this.lat is not a function 异常。

我正在使用 asp.net mvc - 是否有任何框架可以让这更容易?我真的需要帮助。谢谢。

【问题讨论】:

标签: javascript jquery asp.net-mvc google-maps google-maps-api-2


【解决方案1】:

如果你卡住了 2 天,也许重新开始 v3 会是一件好事,这个剪断对我来说是一个类似的工作......

          function GetLocation(address) {
          var geocoder = new google.maps.Geocoder();
          geocoder.geocode({ 'address': address }, function (results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                  ParseLocation(results[0].geometry.location);

              }
              else
                alert('error: ' + status);

          });
      }

  }

  function ParseLocation(location) {

      var lat = location.lat().toString().substr(0, 12);
      var lng = location.lng().toString().substr(0, 12);

      //use $.get to save the lat lng in the database
      $.get('MatchLatLang.ashx?action=setlatlong&lat=' + lat + '&lng=' + lng,
            function (data) {
                // fill textboss (feedback purposes only) 
                //with the found and saved lat lng values
                $('#tbxlat').val(lat);
                $('#tbxlng').val(lng);
                $('#spnstatus').text(data);


            });
    }

【讨论】:

  • 你使用 $.get() 而不是 $.post() 的任何原因
  • 我正在使用 <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 链接 v3 谷歌地图,这是正确的吗?我仍然得到 this.lat() is not a function。
  • "任何你使用 $.get() 而不是 $.post() 的理由 " 不是真的,只是因为它只是少量的数据......
【解决方案2】:

你试过了吗?

$(".geocodethis").click(function () {
    var geocoder = new GClientGeocoder();
    var postalCode = $(this).siblings(".postal").val();
    var id = $(this).siblings(".id").val();

    geocoder.getLatLng(postalCode, function (point) {
        if (!point) {
            alert(postalCode + " not found");
        } else {
            alert(point);
            var marker = new GMarker(point);
            map.addOverlay(marker);
            obj = {lat: marker.position.lat(),
                   lng: marker.position.lng()};
            $.post("/Demographic/Geocode/" + id, obj, function () {
                alert("success?");
            });
        }
    });

});

我很久没用V2了,所以我不确定确切的语法,但重点是根据你需要的信息(lat/lng)创建一个对象并序列化那个。

此外,如果可行的话,强烈建议升级到 V3。

【讨论】:

    【解决方案3】:

    您需要在地图上设置一个标记,这需要一个纬度/经度。您可以根据需要保存该信息或立即显示。 (为了演示目的,代码被截断)

    map = new google.maps.Map(document.getElementById("Map"), myOptions);
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {      
            var marker = new google.maps.Marker({
                position: results[0].geometry.location
            });
            marker.setMap(map);
        }
    }
    

    更新(适用于 v2)

    $(".geocodethis").click(function () {
        var geocoder = new GClientGeocoder();
        var postalCode = $(this).siblings(".postal").val();
        var id = $(this).siblings(".id").val();
    
        geocoder.getLatLng(postalCode, function (point) {
            if (!point) {
                alert(postalCode + " not found");
            } else {
                map.setCenter(point, 13);
                var marker = new GMarker(point);
                map.addOverlay(marker);
            }
        });
    
    });
    

    【讨论】:

    • 我认为他正在使用基于 GClientGeocoder 的 google map v2 api
    • 好的,结果对我来说很重要,它是一个数组吗?所以结果[0] 是Y,结果[1] 是X?因为它不允许我保存结果。还是我保存标记?
    • 抱歉,感谢@kjy112 注意到您使用的是 v2。但是,对于 v3,results[0] 只是搜索的顶部结果,results[0].geometry.location 是顶部结果的完整纬度/经度。
    • 啊,好吧 - 那么...我要为 v2 做什么?
    • :( 我仍然收到this.lat is not a function
    【解决方案4】:

    在 V3 中,坐标必须首先序列化为字符串,如 Arnoldiuss 所示,然后作为 json 发布数据发送。

    var lat = latlong.lat().toString().substr(0, 12); var lng = latlong.lng().toString().substr(0, 12);

    【讨论】:

      【解决方案5】:
      <html>
      <head>
      <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
      
      <%@ taglib prefix="s" uri="/struts-tags"%>
      <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyDS1d1116agOa2pD9gpCuvRDgqMcCYcNa8&sensor=false"></script>
      <script type="text/javascript">
      function initialize() {
      
          var latitude = document.getElementById("latitude").value;
          latitude = latitude.split(",");
      
          var longitude = document.getElementById("longitude").value;
          longitude = longitude.split(",");
      
          var locName = document.getElementById("locName").value;
          locName = locName.split(",");
      
          var RoadPathCoordinates = new Array();
          RoadPathCoordinates.length = locName.length;
      
          var locations = new Array();
          locations.length = locName.length;
      
          var infowindow              = new google.maps.InfoWindow();
          var marker, i;
          var myLatLng                = new google.maps.LatLng(22.727622,75.895719);
      
      
      
          var mapOptions = {
              zoom            : 16,
              center          : myLatLng,
              mapTypeId       : google.maps.MapTypeId.ROADMAP
          };
          var map                     = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
      
      
          //To Draw a line
          for (i = 0; i < RoadPathCoordinates.length; i++)
              RoadPathCoordinates[i] = new google.maps.LatLng(latitude[i],longitude[i]);
          var RoadPath = new google.maps.Polyline({
              path            : RoadPathCoordinates,
              strokeColor     : "#FF0000",
              strokeOpacity   : 1.0,
              strokeWeight    : 2
          });
      
      
          //Adding Marker to given points
          for (i = 0; i < locations.length; i++)
              locations[i] = [locName[i],latitude[i],longitude[i],i+1];
          for (i = 0; i < locations.length; i++) 
          {marker = new google.maps.Marker({
                      position    : new google.maps.LatLng(locations[i][1], locations[i][2]),
                      map         : map
                      });
      
      
      
          //Adding click event to show Popup Menu
          var LocAddress ="";
          google.maps.event.addListener(marker, 'click', (function(marker, i) 
            { return function() 
              {
                  GetAddresss(i);
      
                  //infowindow.setContent(locations[i][0]);
      
                  infowindow.setContent(LocAddress);
                  infowindow.open(map, marker);
              }
            })(marker, i));}
      
      
       function GetAddresss(MarkerPos){
              var geocoder = null;
              var latlng;
              latlng = new google.maps.LatLng(latitude[MarkerPos],longitude[MarkerPos]);
              LocAddress = "91, BAIKUNTHDHAAM"; //Intializing just to test
      
              //geocoder = new GClientGeocoder(); //not working
              geocoder = new google.maps.Geocoder();
      
              geocoder.getLocations(latlng,function ()
              {
                  alert(LocAddress);
                  if (!response || response.Status.code != 200) {
                      alert("Status Code:" + response.Status.code);
                  } else 
                  {
                      place = response.Placemark[0];
                      LocAddress = place.address;
                  }
      
              });
       }
      
          //Setting up path
          RoadPath.setMap(map);   
      }
      </script>
      
      </head>
      <body onload="initialize()">
          <s:form action="mapCls" namespace="/">
              <s:hidden key="latitude" id="latitude"/>
              <s:hidden key="longitude" id="longitude"/>
              <s:hidden key="locName" id="locName"/>
              <div id="map_canvas" style="float:left;width:70%;height:100%"></div>
          </s:form>
      </body>
      </html>
      
      
      I am doing reverse Geocoding, and want address of marker using lat and longitude. M facing problem with function "GetAddresss()", line "geocoder.getLocations(latlng,function ()" is not working properly. what should I Do?
      

      【讨论】:

        猜你喜欢
        • 2021-10-21
        • 2019-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-09
        • 2018-01-13
        • 2020-10-04
        • 2013-07-30
        相关资源
        最近更新 更多