Javascript Function - Convert Geolocation Code to

2020-07-14 16:35发布

问题:

I am looking for a javascript function or jquery library to convert geolocation code (e.g. 42.2342,32.23452) to street address

For examples.

    navigator.geolocation.getCurrentPosition(
      function(pos) {
        $("#lat_field").val(pos.coords.latitude);
        $("#long_field").val(pos.coords.longitude);
      }
    );

Here is a google api URL to get address data

http://maps.googleapis.com/maps/api/geocode/json?latlng=41.03531125,29.0124264&sensor=false

I want to see "formatted_address" : "Hacı Hesna Hatun Mh., Paşa Limanı Cd 2-26, 34674 Istanbul, Türkiye",

    navigator.geolocation.getCurrentPosition(
      function(pos) {
        $("#lat_field").val(pos.coords.latitude);
        $("#long_field").val(pos.coords.longitude);
        $("#adress_data").getaddrfromlatlong(pos.coords.latitude,pos.coords.longitude)
      }
    );

This function should be how ? ``getaddrfromlatlong()

回答1:

Try this:

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">     
   var geocoder = new google.maps.Geocoder();
   var latLng = new google.maps.LatLng(41.03531125,29.0124264);

   if (geocoder) {
      geocoder.geocode({ 'latLng': latLng}, function (results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
            console.log(results[0].formatted_address);
         }
         else {
            console.log("Geocoding failed: " + status);
         }
      });
   }    
</script>


回答2:

I haven't done it in Javascript but I did something similar using the google maps web service to download XML and parse the data out of it. They also have a JSON interface as well which is likely what you'd want to use. It really is rather trivial (download the data, then grep it) so I don't think you'll need a prewritten library for it.