Javascript 如何使用 Google Maps geocoder.getLatLng() 并将其结果存储在数据库中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5782611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:48:22  来源:igfitidea点击:

How do I use Google Maps geocoder.getLatLng() and store its result in a database?

javascriptjqueryasp.net-mvcgoogle-mapsgoogle-maps-api-2

提问by Grahame A

Hey everybody! Im trying to use getLatLng() to geocode a list of postal/zip codes and store the generated point in the database to be placed on a map later. This is what I've got so far:

大家好!我尝试使用 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?");
    });
}

but I'm getting this.lat is not a functionin my error console when i try to serialize the point object or use it in $.post()

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

From my research, I understand that geocoder.getLatLng()is asynchronous, how would that affect what I'm trying to do? I'm not running this code in a loop, and I'm trying to post the point using the anonymous callback function.

从我的研究中,我知道这geocoder.getLatLng()是异步的,这将如何影响我正在尝试做的事情?我不是在循环中运行此代码,而是尝试使用匿名回调函数发布该点。

How can I save the information from pointto use later?

如何保存信息point以备后用?

Update

更新

Creating a marker and trying to post that still results in the this.lat is not a functionin the error console.

创建一个标记并尝试发布它仍然会导致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?");
                });
            }
        });

    });

** Another Update **

** 另一个更新 **

I really need to save the geocoded address for later, even if I store the latitude/longitude values in my database and remake the marker when I'm ready to put it onto a map. Again, serializing or posting - seemingly using the point in any way other than in google maps functions gives the this.lat is not a functionexception in my error log.

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

I'm using asp.net mvc - are there any frameworks out there that would make this easier? I really need help with this. Thanks.

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

回答by Arnoldiusss

If your stuck for 2 days maybe a fresh v3 start would be a good thing, this snipped does a similair job for me...

如果您卡住了 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);


            });
    }

回答by Herman Schaaf

Have you tried this?

你试过这个吗?

$(".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?");
            });
        }
    });

});

I haven't used V2 in a long time, so I'm not sure about the exact syntax, but the point is to create an object from the information you need (lat/lng) and serialize that.

我没有使用V2在很长一段时间,所以我不知道确切的语法,但关键是要创建一个从信息的对象,你需要(纬度/经度)和序列化那个

Also, an upgrade to V3 is much recommended, if plausible.

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

回答by peterincumbria

In V3 the coordinates must be first serialized as a string as shown by Arnoldiuss, before sending as json post data.

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

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

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

回答by Dustin Laine

You need to set a marker on the map, which takes a lat/long. You can save that info however you want or display immediately. (Code truncated for demo purpose)

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

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);
    }
}

UPDATE (FOR v2)

更新(适用于 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);
        }
    });

});

回答by Suruchi

<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?