Country name for GPS coordinates

后端 未结 6 1775
南笙
南笙 2020-12-05 07:46

Is there an easy way to get the name of the country on whose territory a given point is located?

I don\'t care too much about accuracy nor about ambiguities given by

6条回答
  •  执念已碎
    2020-12-05 08:26

    Here's some JavaScript code to get the name of the country from latitude and longitude coordinates:


    1. Using Google's geocoding services [jsfiddle]:

      var lookupCountryWithGoogle = function(lat, lng) { var latlng = new google.maps.LatLng(lat, lng);

      var geoCoder = new google.maps.Geocoder();
      
      geoCoder.geocode({
          location: latlng
      }, function(results, statusCode) {
          var lastResult = results.slice(-1)[0];
      
          if (statusCode == 'OK' && lastResult && 'address_components' in lastResult) {
              alert('coordinates: ' + lat + ', ' + lng + '\n' + 'country: ' + lastResult.address_components.slice(-1)[0].long_name);
          } else {
              alert('coordinates: ' + lat + ', ' + lng + '\n' + 'failed: ' + statusCode);
          }
      });
      

      };

      lookupCountryWithGoogle(43.7534932, 28.5743187); // will succeed lookupCountryWithGoogle(142, 124); // will fail

    (You'll need to load Google's JavaScript support for this from a URL such as maps.google.com/maps/api/js?sensor=false&fake=.js)


    1. Using ws.geonames.org [jsfiddle]:

      var lookupCountryWithGeonames = function(lat, lng) {

      $.getJSON('http://ws.geonames.org/countryCode', {
          lat: lat,
          lng: lng,
          type: 'JSON'
      }, function(results) {
          if (results.countryCode) {
              alert('coordinates: ' + lat + ', ' + lng + '\n' + 'country: ' + results.countryName);
          } else {
              alert('coordinates: ' + lat + ', ' + lng + '\n' + 'failed: ' + results.status.value + ' ' + results.status.message);
          }
      });
      

      };

      lookupCountryWithGeonames(43.7534932, 28.5743187); // will succeed

      lookupCountryWithGeonames(142, 124); // will fail ​

提交回复
热议问题