Google geocoder - Asynchronous request return "undefined" value - javascript

I have this function that should return the country starting from the latitude and longitude and assign it to a global variable declare outside the function. I know that the a in Ajax stand for asynchronous and I have read every single answer on stackoverflow but I can't fix it.
function getLatLongDetail(myLatlng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': myLatlng },
function (results, status) {
var country = "";
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
// check if this entry in address_components has a type of country
if (addr.types[0] == 'country')
country = addr.long_name;
}
}
return country; // this doesn't work
}
}
});
}
var Country = getLatLongDetail(myLatlng);
alert(Country);// undefined
I know there are hundreds of questions about callback function but none of them worked for me.

Finally I made it! Here the code:
function getLatLongDetail(myLatlng, fn) {
var geocoder = new google.maps.Geocoder();
var country = "";
var city = "";
var address = "";
var zip = "";
var state = "";
geocoder.geocode({ 'latLng': myLatlng },
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
// check if this entry in address_components has a type of country
if (addr.types[0] == 'country')
country = addr.long_name;
else if (addr.types[0] == ['locality']) // City
city = addr.long_name;
else if (addr.types[0] == 'street_address') // address 1
address = address + addr.long_name;
else if (addr.types[0] == 'establishment')
address = address + addr.long_name;
else if (addr.types[0] == 'route') // address 2
address = address + addr.long_name;
else if (addr.types[0] == 'postal_code') // Zip
zip = addr.short_name;
else if (addr.types[0] == ['administrative_area_level_1']) // State
state = addr.long_name;
}
}
fn(country,city, address, zip, state);
}
});
}
var mCountry; //global variable to store the country
vat mCity; //global variable to store the city
getLatLongDetail(event.latLng, function(country,city, address, zip, state){
mCountry = country; // now mCountry store the value from getLatLongDetail so I can save it in the database
mCity = city;
alert(address + zip + state);
});

Related

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;

google geocoding address breakdown

I am very new to this and would like to know how to get the full string and not the first character as it is currently doing,
currently using the example of the html + js from https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
function codeLatLng(callback) {
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]) {
map.setZoom(17);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
document.getElementById('Addressb').value= results[0].formatted_address; //working
document.getElementById('Strn').value = results[0].formatted_address[0];
document.getElementById('Strna').value = results[0].formatted_address[2];
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
the results needs to get stored in the specified text fields as bellow
Street Number: <input id="Strn" type="text"><br>
Street Name: <input id="Strna" type="text"><br>
Suburb: <input id="Subu" type="text"><br>
Town: <input id="Town" type="text"><br>
Code: <input id="Code1" type="text"><br>
You have to iterate through the address components and then the types, here is the code
var streetNumber;
var streetName;
var city;
var state;
var zip;
var country;
for(var i = 0; i < results[0].address_components.length; i++){
for(var k = 0; k < results[0].address_components[i].types.length; k++){
if (results[0].address_components[i].types[k] == "street_number")
streetNumber = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "route")
streetName = results[0].address_components[i].short_name;
else if (results[0].address_components[i].types[k] == "locality")
city = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "administrative_area_level_1")
state = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "postal_code")
zip = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "country")
country = results[0].address_components[i].long_name;
}
}
Here's a link the Google Maps Geocoding docs, specifying the format of the response.
It looks like it does return the components of the address separately, in the address_components array, in a specific order. So if you're geocoding a street address, address_components[0].long_name should return the street address, address_components[1].long_name the street name, etc.
Hope that helps.

Find a location with geocoder but only using city, not using street

for example:
var city, country;
geocoder.geocode(
{'address': city + ', ' + country}, function(results, status) {}
);
the problem is when the var city is wrong and is a random streetname (in a random city)
he puts this location in results, but I only want cities...
Is there a way to use geocode() only for searching a city?
//get address info such as city and state from lat and long
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
//break down the three dimensional array into simpler arrays
for (i = 0 ; i < results.length ; ++i)
{
var super_var1 = results[i].address_components;
for (j = 0 ; j < super_var1.length ; ++j)
{
var super_var2 = super_var1[j].types;
for (k = 0 ; k < super_var2.length ; ++k)
{
//find city
if (super_var2[k] == "locality")
{
//put the city name in the form
main_form.city.value = super_var1[j].long_name;
}
//find county
if (super_var2[k] == "administrative_area_level_2")
{
//put the county name in the form
main_form.county.value = super_var1[j].long_name;
}
//find State
if (super_var2[k] == "administrative_area_level_1")
{
//put the state abbreviation in the form
main_form.state.value = super_var1[j].short_name;
}
}
}
}
}

How to get city name from latitude and longitude in phone gap?

I am able to get get full address from current latitude and longitude. but how can I get only city name from full address. this is my code.
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
//alert("Else loop" + latlng);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
//alert("Else loop1");
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add = results[0].formatted_address;
alert("Full address is: " + add);
} else {
alert("address not found");
}
} else {
//document.getElementById("location").innerHTML="Geocoder failed due to: " + status;
//alert("Geocoder failed due to: " + status);
}
});
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];
alert("city name is: " + city);
}
else {
alert("address not found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
}
);
Split the full address with "," as delimiter and get the city name..
Clean example to get location from lat and lang and parsing result. based on Google Reverse Geocoding
var geocodingAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng=23.714224,78.961452&key=YOUR_SERVER_API_KEY";
$.getJSON(geocodingAPI, function (json) {
if (json.status == "OK") {
//Check result 0
var result = json.results[0];
//look for locality tag and administrative_area_level_1
var city = "";
var state = "";
for (var i = 0, len = result.address_components.length; i < len; i++) {
var ac = result.address_components[i];
if (ac.types.indexOf("administrative_area_level_1") >= 0) state = ac.short_name;
}
if (state != '') {
console.log("Hello to you out there in " + city + ", " + state + "!");
}
}
});
You can find documentation here :
https://developers.google.com/maps/documentation/geocoding/?hl=fr#ReverseGeocoding
But you can see in your "results" which item is the city without spliting the object.
So you can do :
country=results[0]['address_components'][6].long_name;
state=results[0]['address_components'][5].long_name;
city=results[0]['address_components'][4].long_name;
Be carefull, the numbers "4,5,6" can change by the country. So it safier to test like that :
Getting street,city and country by reverse geocoding using google
Take a look at Google Reverse Geocoding
http://maps.google.com/maps/api/geocode/xml?latlng=YourLatitude,YourLongitude&sensor=false&key=API_KEY
This is already asked here
This is how I I'm doing it. Was afraid to use a comma delimiter.
function ReverseGeoToCity(lat, lng, callback) {
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 properName = ", ";
for(i=0; i<results[1].address_components.length; i++){
if (results[1].address_components[i].types[0] == "locality")
properName = results[1].address_components[i].short_name + properName;
if (results[1].address_components[i].types[0] == "administrative_area_level_1")
properName += results[1].address_components[i].short_name;
}
callback(properName);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
Below code will help you for get city name From latitude and longitude:
var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&key=KEY_HERE&sensor=false";
$.get(url, function(data) {
var results = data.results;
if (data.status === 'OK')
{
//console.log(JSON.stringify(results));
if (results[0])
{
var city = "";
var address_components = results[0].address_components;
for (var i = 0; i < address_components.length; i++)
{ state = address_components[i].long_name;
}
if (address_components[i].types[0] === "locality" && address_components[i].types[1] === "political" ) {
city = address_components[i].long_name;
}
}
alert("CITY : " + city );
}
else
{
window.alert('No results found');
}
}
else
{
window.alert('Geocoder failed due to: ' + status);
}
});

Geocoding with Google and Jquery

I'm new to jquery but I am having a bit of a hard time at the moment. This is as far as I can get, the eventual idea is to do the following:
User types in an address and clicks search
Google Geocoder runs
Either error if not result, or grab co-ordinates, state, zip, country, city and print in a message box
The code I have at the moment is not even able to complete the process of grabbing the coordinates from the input box. It keeps telling me it is expecting a bracket but no matter where I put the bracket I cannot get it to run.
This is my trying to run:
http://jsfiddle.net/QA7Xr/16/
Here is the complete code:
var myLatlng = new google.maps.LatLng(31.272410, 0.190898);
// INITALIZATION
function initialize() {
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
// GEOCODE
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("Geocode was successful");
};
} else {
alert("Geocode was not successful for the following reason: " + status);
};
};
}
// GET ADDRESS DETAILS
function getLatLongDetail() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': myLatlng
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var address = "",
city = "",
state = "",
zip = "",
country = "";
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
// check if this entry in address_components has a type of country
if (addr.types[0] == 'country') country = addr.long_name;
else if (addr.types[0] == 'street_address') // address 1
address = address + addr.long_name;
else if (addr.types[0] == 'establishment') address = address + addr.long_name;
else if (addr.types[0] == 'route') // address 2
address = address + addr.long_name;
else if (addr.types[0] == 'postal_code') // Zip
zip = addr.short_name;
else if (addr.types[0] == ['administrative_area_level_1']) // State
state = addr.long_name;
else if (addr.types[0] == ['locality']) // City
city = addr.long_name;
}
alert('City: ' + city + '\n' + 'State: ' + state + '\n' + 'Zip: ' + zip + '\n' + 'Country: ' + country);
}
}
});
}
initialize();
getLatLongDetail();
Can anyone tell me where I am going wrong please? I've hit a dead end with this.
Your JS was a mess, I've tidied it up: http://jsfiddle.net/QA7Xr/19/
In order:
Two extra close brackets in a function
You used getElementById() using an ID that did not exist
You bound an onClick when a JS assignment is easier
Your geocoder var was local within getLatLongDetail. You needed it in codeAddress, so I've made it global.
Points to improve:
Wrap your code in a closure to avoid namespace pollution
Use the Google events to control your code assignments. Right now, if a user clicks too quickly, your code will throw up
Simplify the logic
Here is the updated link,
http://jsfiddle.net/QA7Xr/24/
geocoder.geocode({}, function(){....}); /*not closed properly*/
and there are improper usage of semicolon.

Categories