Adakah cara untuk mendapatkan nama kota dari titik lintang dan bujur dengan menggunakan api google maps untuk javascript?
Jika demikian, bisakah saya melihat contoh?
javascript
node.js
google-maps
geocoding
latitude-longitude
Dennis Martinez
sumber
sumber
Jawaban:
Ini disebut Geocoding Terbalik
Dokumentasi dari Google:
http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding .
Contoh Panggilan ke Layanan Web geocode Google:
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true&key=YOUR_KEY
sumber
Berikut contoh lengkapnya:
<!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>
sumber
Di node.js kita dapat menggunakan modul node-geocoder npm untuk mendapatkan alamat dari 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); });
keluaran:
[ { 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' } ]
sumber
Berikut adalah contoh terbaru dari Layanan Web geocode Google
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY
Cukup ubah
YOUR_API_KEY
ke kunci API yang Anda dapatkan dari Google Geocoding APIP / S: Geocoding API ada di bawah Places BUKAN Maps ;)
sumber
Berikut solusi modern menggunakan janji:
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(); }); };
Dan sebut saja seperti ini:
getAddress(lat, lon).then(console.log).catch(console.error);
Promise mengembalikan objek alamat di 'then' atau kode status kesalahan di 'catch'
sumber
Kode Berikut Berfungsi dengan Baik untuk Mendapatkan Nama Kota (Menggunakan Google Map Geo API ):
HTML
<p><button onclick="getLocation()">Get My Location</button></p> <p id="demo"></p> <script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>
NASKAH
var x=document.getElementById("demo"); function getLocation(){ if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(showPosition,showError); } else{ x.innerHTML="Geolocation is not supported by this browser."; } } function showPosition(position){ lat=position.coords.latitude; lon=position.coords.longitude; displayLocation(lat,lon); } function showError(error){ switch(error.code){ case error.PERMISSION_DENIED: x.innerHTML="User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML="Location information is unavailable." break; case error.TIMEOUT: x.innerHTML="The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML="An unknown error occurred." break; } } function displayLocation(latitude,longitude){ var geocoder; geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(latitude, longitude); geocoder.geocode( {'latLng': latlng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[0]) { var add= results[0].formatted_address ; var value=add.split(","); count=value.length; country=value[count-1]; state=value[count-2]; city=value[count-3]; x.innerHTML = "city name is: " + city; } else { x.innerHTML = "address not found"; } } else { x.innerHTML = "Geocoder failed due to: " + status; } } ); }
sumber
Sama seperti @Sanchit Gupta.
di bagian ini
if (results[0]) { var add= results[0].formatted_address ; var value=add.split(","); count=value.length; country=value[count-1]; state=value[count-2]; city=value[count-3]; x.innerHTML = "city name is: " + city; }
hanya menghibur larik hasil
if (results[0]) { console.log(results[0]); // choose from console whatever you need. var city = results[0].address_components[3].short_name; x.innerHTML = "city name is: " + city; }
sumber
Ada banyak alat yang tersedia
alat gratis dan berbayar lainnya juga tersedia
sumber
BigDataCloud juga memiliki API yang bagus untuk ini, juga untuk pengguna nodejs.
mereka memiliki API untuk klien - gratis . Tapi juga untuk backend , menggunakan API_KEY (gratis sesuai kuota).
Halaman GitHub mereka .
kodenya terlihat seperti:
const client = require('@bigdatacloudapi/client')(API_KEY); async foo() { ... const location: string = await client.getReverseGeocode({ latitude:'32.101786566878445', longitude: '34.858965073072056' }); }
sumber
Jika Anda tidak ingin menggunakan Google geocoding API daripada Anda dapat merujuk ke beberapa API Gratis lainnya untuk tujuan pengembangan. misalnya saya menggunakan [mapquest] API untuk mendapatkan nama lokasi.
Anda dapat mengambil nama lokasi dengan mudah dengan menerapkan fungsi berikut ini
const fetchLocationName = async (lat,lng) => { await fetch( 'https://www.mapquestapi.com/geocoding/v1/reverse?key=API-Key&location='+lat+'%2C'+lng+'&outFormat=json&thumbMaps=false', ) .then((response) => response.json()) .then((responseJson) => { console.log( 'ADDRESS GEOCODE is BACK!! => ' + JSON.stringify(responseJson), ); }); };
sumber
Anda dapat melakukannya dengan php murni dan api geocode google
/* * * @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; } }
sumber