To find the address of a location, first you need to find our latitude and longitude. This can be done my following the blog about finding latitude and longitude
Once the latitude and longitude are in place, they can be passed to Google reverse geocoding api to find the details of the location. Please read the terms and conditions of Google geocoding api also.
<script type="text/javascript">
function findLocation(latitude,longitude){
var request = new XMLHttpRequest();
var method = 'GET';
var url = 'https://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);
console.log(data);
}
};
request.send();
};
</script>
On success this returns back the response containing the details of the address. Look into the print of console after running this javascript and you will see yourself. Also each address component has a level though which you can figure out specific details. For example to find the city and state of the address, you can write the code as follows:
var city;
var state;
var arrayLength = data.results[0].address_components.length;
for (var i = 0; i < arrayLength; i++) {
if(data.results[0].address_components[i].types[0]
== 'administrative_area_level_2'){
city = data.results[0].address_components[i].long_name;
}else if(data.results[0].address_components[i].types[0]
== 'administrative_area_level_1'){
state = data.results[0].address_components[i].long_name;
}
}
No comments:
Post a Comment