How can I get city name from a latitude and longitude point?

后端 未结 11 1163
感情败类
感情败类 2020-11-28 03:07

Is there a way to get a city name from a latitude and longitude point using the google maps api for javascript?

If so could I please see an example?

相关标签:
11条回答
  • 2020-11-28 03:23

    Here's a modern solution using a promise:

    function getAddress (latitude, longitude) {
        return new Promise(function (resolve, reject) {
            var request = new XMLHttpRequest();
    
            var method = 'GET';
            var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true';
            var async = true;
    
            request.open(method, url, async);
            request.onreadystatechange = function () {
                if (request.readyState == 4) {
                    if (request.status == 200) {
                        var data = JSON.parse(request.responseText);
                        var address = data.results[0];
                        resolve(address);
                    }
                    else {
                        reject(request.status);
                    }
                }
            };
            request.send();
        });
    };
    

    And call it like this:

    getAddress(lat, lon).then(console.log).catch(console.error);
    

    The promise returns the address object in 'then' or the error status code in 'catch'

    0 讨论(0)
  • 2020-11-28 03:24

    There are many tools available

    1. google maps API as like all had written
    2. use this data "https://simplemaps.com/data/world-cities" download free version and convert excel to JSON with some online converter like "http://beautifytools.com/excel-to-json-converter.php"
    3. use IP address which is not good because using IP address of someone may not good users think that you can hack them.

    other free and paid tools are available also

    0 讨论(0)
  • 2020-11-28 03:31

    you can do it with pure php and google geocode api

    /*
     *
     * @param latlong (String) is Latitude and Longitude with , as separator for example "21.3724002,39.8016229"
     **/
    function getCityNameByLatitudeLongitude($latlong)
    {
        $APIKEY = "AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Replace this with your google maps api key 
        $googleMapsUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $latlong . "&language=ar&key=" . $APIKEY;
        $response = file_get_contents($googleMapsUrl);
        $response = json_decode($response, true);
        $results = $response["results"];
        $addressComponents = $results[0]["address_components"];
        $cityName = "";
        foreach ($addressComponents as $component) {
            // echo $component;
            $types = $component["types"];
            if (in_array("locality", $types) && in_array("political", $types)) {
                $cityName = $component["long_name"];
            }
        }
        if ($cityName == "") {
            echo "Failed to get CityName";
        } else {
            echo $cityName;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 03:37

    Here is a complete sample:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Geolocation API with Google Maps API</title>
        <meta charset="UTF-8" />
      </head>
      <body>
        <script>
          function displayLocation(latitude,longitude){
            var request = new XMLHttpRequest();
    
            var method = 'GET';
            var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true';
            var async = true;
    
            request.open(method, url, async);
            request.onreadystatechange = function(){
              if(request.readyState == 4 && request.status == 200){
                var data = JSON.parse(request.responseText);
                var address = data.results[0];
                document.write(address.formatted_address);
              }
            };
            request.send();
          };
    
          var successCallback = function(position){
            var x = position.coords.latitude;
            var y = position.coords.longitude;
            displayLocation(x,y);
          };
    
          var errorCallback = function(error){
            var errorMessage = 'Unknown error';
            switch(error.code) {
              case 1:
                errorMessage = 'Permission denied';
                break;
              case 2:
                errorMessage = 'Position unavailable';
                break;
              case 3:
                errorMessage = 'Timeout';
                break;
            }
            document.write(errorMessage);
          };
    
          var options = {
            enableHighAccuracy: true,
            timeout: 1000,
            maximumAge: 0
          };
    
          navigator.geolocation.getCurrentPosition(successCallback,errorCallback,options);
        </script>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-11-28 03:37

    In node.js we can use node-geocoder npm module to get address from lat, lng.,

    geo.js

    var NodeGeocoder = require('node-geocoder');
    
    var options = {
      provider: 'google',
      httpAdapter: 'https', // Default
      apiKey: ' ', // for Mapquest, OpenCage, Google Premier
      formatter: 'json' // 'gpx', 'string', ...
    };
    
    var geocoder = NodeGeocoder(options);
    
    geocoder.reverse({lat:28.5967439, lon:77.3285038}, function(err, res) {
      console.log(res);
    });
    

    output:

    node geo.js

    [ { formattedAddress: 'C-85B, C Block, Sector 8, Noida, Uttar Pradesh 201301, India',
        latitude: 28.5967439,
        longitude: 77.3285038,
        extra: 
         { googlePlaceId: 'ChIJkTdx9vzkDDkRx6LVvtz1Rhk',
           confidence: 1,
           premise: 'C-85B',
           subpremise: null,
           neighborhood: 'C Block',
           establishment: null },
        administrativeLevels: 
         { level2long: 'Gautam Buddh Nagar',
           level2short: 'Gautam Buddh Nagar',
           level1long: 'Uttar Pradesh',
           level1short: 'UP' },
        city: 'Noida',
        country: 'India',
        countryCode: 'IN',
        zipcode: '201301',
        provider: 'google' } ]
    
    0 讨论(0)
提交回复
热议问题