How to get address from lat and lng? - javascript

I have two set of lat and lng.
I want both address and stored in some variable:
var geocoder = new google.maps.Geocoder();
for(var i=0; i<json_devices.length; i++)
{
var lat = json_devices[i].latitude;
var lng = json_devices[i].longitude;
console.log(lat);
console.log(lng);
var latlng = new google.maps.LatLng(lat,lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
address=results[1].formatted_address;
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
console.log(address);
}
In this, lat & lan get correctly. But address are not stored in variable. What is the mistake?

I am using this method and it is working perfect for me.
Please have a look on it.
public String getAddressFromLatLong(GeoPoint point) {
String address = "Address Not Found";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
address =addresses.get(0).getAddressLine(0);
if(address.length()<=0)
address =addresses.get(0).getSubLocality();
}
}
catch (Exception e) {
e.printStackTrace();
}
return address;
}

Here the Google geocode is asynchonous type of function call.
From DOCS:
Accessing the Geocoding service is asynchronous, since the Google Maps
API needs to make a call to an external server. For that reason, you
need to pass a callback method to execute upon completion of the
request. This callback method processes the result(s). Note that the
geocoder may return more than one result.
So you can't get the address like that, instead use the common approach called callback.
Here I have created a sample code to explain the process, which can be altered by yourself.
var geocoder;
function codeLatLng(callback) {
geocoder = new google.maps.Geocoder();
var input = document.getElementById("latlng").value;
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
address = results[1].formatted_address;
callback(address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
$('input[type="button"]').on('click', function () {
codeLatLng(function (address) { //function call with a callback
console.log(address); // THE ADDRESS WILL BE OBTAINED
})
});
JSFIDDLE

Related

Variable overwritten by ajax response

Using Google Maps and the Geocoder, I'm trying to loop over an object of addresses, return LatLng addresses for them, and create markers using both the original details and the latlng address in the setMarker function below.
The problem is, the response[a] is being overwritten by the last address in the object, because the for loop is running ahead of the AJAX results being returned.
How can I save the data in the current response[a] being looped over, so that when setMarker() is later called, it contains the right information?
Thanks
var limit = 0;
for (a in response){
if(limit<5){ // limit API calls
var addr = [response[a].Addr1, response[a].City, response[a].Zip];
geo = new google.maps.Geocoder();
geo.geocode({
address: addr.join(", "),
componentRestrictions: {
// country: 'UK'
}
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
if(latitude!="" && longitude!=""){
bounds.extend(latlng);
map.fitBounds(bounds);
_this.setMarker(map, limit, latlng, response[a]);
}
} // if geo results
});
}
limit++;
}
The problem you are facing is a classic one that can be solved using closure function.
Current code looks something like :
var a[20];
for(i=0;i<20;i++) {
some_async_method() {
//code that uses 'a[i]'
}
}
Using closure to preserve the scope of var a inside a async function :
var a[20];
for(i=0;i<20;i++) {
(function(_a){
some_async_method() {
//code that uses 'a[i]' as '_a'
}
})(a[i]);// self calling function that preserves the scope of a[i]
}
So your code will look like :
var limit = 0;
for (a in response){
if(limit<5){ // limit API calls
var addr = [response[a].Addr1, response[a].City, response[a].Zip];
geo = new google.maps.Geocoder();
(function(response_a){ // closure function to preserve scope of 'response[a]'
geo.geocode({
address: addr.join(", "),
componentRestrictions: {
// country: 'UK'
}
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
if(latitude!="" && longitude!=""){
bounds.extend(latlng);
map.fitBounds(bounds);
_this.setMarker(map, limit, latlng, response_a);
}
} // if geo results
});
})(response[a]);
}
limit++;
}

Getting error Geocoder failed while fetching current location using JavaScript

I am getting the following error while trying to fetch current location using Google Maps API.
Error:
Geocoder failed
I am providing my code below.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
function getDefaultLocation(){
setTimeout(function(){
var geocoder='';
geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
console.log("Geocoder failed");
}
function codeLatLng(lat, lng){
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK){
if (results[1]) {
var indice=0;
for (var j=0; j<results.length; j++){
if (results[j].types[0]=='locality'){
indice=j;
break;
}
for (var i=0; i<results[j].address_components.length; i++){
if (results[j].address_components[i].types[0] == "locality") {
city = results[j].address_components[i];
}
if(results[j].address_components[i].types[0] == "administrative_area_level_1"){
region = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "country"){
country = results[j].address_components[i];
}
if(results[j].address_components[i].types[0] == "route"){
locality=results[j].address_components[i];
}
}
}
// console.log('final result',city.long_name,region.long_name,country.long_name,locality.long_name);
var city=city.long_name;
var country=country.long_name;
var locality=locality.long_name;
document.getElementById('bindCon').innerHTML=country; document.getElementById('bindCit').innerHTML=city; document.getElementById('bindloc').innerHTML=locality;
}else{
console.log("No results found");
}
}else{
console.log("Geocoder failed due to: " + status);
}
})
}
},5000);
}
The above code is working properly in localhost but while putting this into my testing site (http://xxxx.com) the above error is coming. Here I need to fetch all the required data.

How to pass javascript alert message value to label in asp.net

I had implemented geolocation , wherein browser gets location of user.
In this code i'm getting geolocation of user through browser ,but it display location using javascript alert message.
I just want to pass alert message value to label or hiddenfield in ASP.Net & doesn't want to run alert message
My javascript code as follows.
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
document.getElementById('<%=Label1.ClientID %>').innerHTML = city;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
If you want to store the value in a hidden field replace
alert(results[0].formatted_address)
with
//hdnField is the ID of your asp:HiddenField object
var hiddenField = document.getElementById("<%= hdnField.ClientID %>")
hiddenField.value = results[0].formatted_address;

GoogleMaps : Return is Not working in Reverse Geocoading

I am trying ReverseGeCoding its working but i cant get return value
function reverseGeoCode(lat,lng) {
var reverseGeoAddress = '';
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
if(results[1].formatted_address.length){
reverseGeoAddress = results[1].formatted_address;
//NOTE: when i console.log(reverseGeoAddress );
//its working fine i am getting the address
return reverseGeoAddress;
//but return not working.
}
}
}
});
}
when i call my function like
var address = reverseGeoCode(31.518945,74.349316);
now every time my address variable is "undefined";
why is this doing so??
Any hint ?
Function reverseGeoCode is not having any return value
return reverseGeoAddress; is inside anonymous function.
Simple fix would be - you can possibly use callback since it is asynchronous function. "callback" can be a handler from the place you invoke.
// Invoking reverseGeoCode....
reverseGeoCode(lat,lng, function(myAddress){
// Your custom code goes here...
});
function reverseGeoCode(lat,lng, callback) {
var reverseGeoAddress = '';
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
if(results[1].formatted_address.length){
reverseGeoAddress = results[1].formatted_address;
// Callback the handler if it exists here
// No return value
callback(reverseGeoAddress);
}
}
}
});
}

Google Map API - Get Address of User

Ive tried several methods to get get a visitors country location using geolocation method but im stil at no avail.
Could someone help atall as I'd like to get a visitors country and write it to a database using ajax.
my current code
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
var country = results[7].formatted_address;
$('.location').text(country);
var dataStrings = 'email=<?php echo $userid;?>&location='+ country;
console.log(dataStrinsg);
$.ajax({
type: "POST",
url: "location-update.php",
data: dataStrings,
success: function() {
location.reload();
}
});
return false;
if (results[1]) {
//formatted address
// alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}</script>
Assuming that you call initalize() before the geocoding(otherwise geocode will be undefined):
You're accessing results[7] here:
var country = results[7].formatted_address;
...but there is no guarantee that results[7] exists.

Categories