Google map Geocoder [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I Using the google geocoder to get the lat and lng, when initMap had been called, I got two alert, first value is undefined ,and second get the lat value, what is the problem to get the undefined value, and how to resolve this? I need to get the value immediately.
function initMap(){
var addr = '1600 Amphitheatre Parkway, Mountain View, CA';
var code = getLatLng(addr);
alert(code.lat); // --> alert_1
}
function getLatLng(addr) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': addr }, function (results, status) {
var lat,lng = 0;
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
}
alert(lat); // --> alert_2
return {lat : lat,lng : lng};
});
}

The function geocode is an asynchronous function. Therefore, you get undefined for code.lat in the alert of the initMap function and the geocoded value in the getLatLng function. You can add a callback function to the parameters of the getLatLng function to solve your problem like this:
function initMap() {
var addr = '1600 Amphitheatre Parkway, Mountain View, CA';
getLatLng(addr, function(code) {
alert(code.lat);
});
}
function getLatLng(addr, cb) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': addr }, function (results, status) {
var lat,lng = 0;
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
}
cb({lat: lat, lng: lng});
});
}

Related

Javascript can't access global variables outside function [duplicate]

This question already has answers here:
Using a callback function with Google Geocode
(1 answer)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
I'm using google map geocoding to get latitude,longitude value from address.Here is my code,
var latd;
var lond;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(place);
var latd = results[0].geometry.location.lat();
var lond = results[0].geometry.location.lng();
}
console.log(latd);
});
//console.log(latd);
When access the variable latd outside function, its value seems undefined. What's the issue with the above code?
Update1:
getlatlang(address);
console.log(latd);//Not defined
function getlatlang(address)
{
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//console.log(place);
latd = results[0].geometry.location.lat();
lond = results[0].geometry.location.lng();
return latd,lond;
}
});
}
If you want to have access to lat, long outside the function simply assign them and do not create them inside. You can read more about JavaScript Scope
var latd;
var lond;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(place);
latd = results[0].geometry.location.lat();
lond = results[0].geometry.location.lng();
}
console.log(latd);
});
//console.log(latd);
First, because the variable you try to access into your condition will be accessible only into the context if. The variable your redeclared into if is new variable.
if (status == google.maps.GeocoderStatus.OK) {
console.log(place);
var latd = results[0].geometry.location.lat();
var lond = results[0].geometry.location.lng();
console.log(latd, lond)
}
You can change with this:
var latd;
var lond;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(place);
latd = results[0].geometry.location.lat();
lond = results[0].geometry.location.lng();
}
console.log(latd);
});
Update
geocoder.geocode is an async function. You have to wait until it's done.
Your variable after the geocoder.geocod is executed even if the geocoder hasn't yet finished to be executed. So your variable is always undefined, because you create a variable with undefined value.
Note: All your action should be into the callback function, of geocoder, otherwise, it will always undefined.

Set variable that is out of function scope, from within function

I'm trying to get the latitude and longitude of a place from a placeId but I'm unsure how to set the variables above the geocode function from within the geocode function. At the moment the console.log in the function gives me valid lat and long values and the second console.log gives me 0.00. How do I set the latitude and longitude variables that start off as 0.00?
$("#search-filter-form").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
//get latlong of area:
var geocoder = new google.maps.Geocoder();
var address = "new york";
var placeId = searchFilterViewModel.searchFilterAutoComplete.placeObject.placeId;
var latitude = 0.00;
var longitude = 0.00;
geocoder.geocode( { 'placeId': placeId}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
console.log(latitude, longitude);
}
});
console.log(latitude, longitude);
}
instead of passing an anonymous func to the submit method you could make it a named one.
then you could define static variables.
function myfunction() {
myfunction.something = 123;
}
now you can access the var from anywhere
myfunction.something
While the duplicate answer and the answer above may have also worked, this is what I did:
Moved the asynchronous function out of the form submission and into a function that runs as soon as there is a latitude and longitude to set - I don't want to risk submitting the form before the latitude and longitude are set.
Turned the anonymous callback function into an arrow callback function so that I can use "this" keyword to point to the parent of the asynchronous function, so that I am setting the parent object variable and not just the function variable:
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'placeId': this.placeObject.placeId}, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
this.placeObject.latitude = results[0].geometry.location.lat();
this.placeObject.longitude = results[0].geometry.location.lng();
}
});

Gmaps Callback function get variables [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I have JS code which is doing geolocation, so I converted address to coordinates, but I can not get values from callback function:
$(function () {
var longitude;
var latitude;
GMaps.geocode({
address: geolocate_address,
callback: function(results, status) {
if (status == 'OK') {
var latlng = results[0].geometry.location;
latitude = latlng.lat();
longitude = latlng.lng();
}
}
});
console.log(latitude);
console.log(longitude);
});
Shows empty variables.
When I do alert in callback function it shows coordinates.
How to get coordinates outside that function?
Your callback is async, at the moment you invoke console.log(latitude);, latitude still does not have value set, as client is still waiting for server response.
Try to handle data after you receive it:
GMaps.geocode({
address: geolocate_address,
callback: function(results, status) {
if (status == 'OK') {
var latlng = results[0].geometry.location;
latitude = latlng.lat();
longitude = latlng.lng();
handleCallback(latitude, longitude);
}
}
});
function handleCallback(latitude, longitude){
console.log(latitude);
console.log(longitude);
}

Asynchronous Google Maps request throwing off Javascript

I'm working on someone else's code, and I am trying to use Google maps API to convert a street address into latitude and longitude coordinates:
var start_lng;
var end_lat;
var end_lng;
getLat(start);
getLng(start);
function getLat(loc) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': loc}, function postcodesearch(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var lat = results[0].geometry.location.lat();
alert(lat);
return lat;
//alert(start_lng);
}
else {
alert("Error");
}
});
}
function getLng(loc) {
var geocoder_lng = new google.maps.Geocoder();
geocoder_lng.geocode({'address': loc}, function postcodesearch(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var lng = results[0].geometry.location.lng();
alert(lng);
return lng;
}
else {
alert("Error");
}
});
}
So far, so good. In the code below, I take that latitude and longitude and perform various calculations with them:
alert("DO REST");
var start_p = new google.maps.LatLng(start_lat, start_lng);
alert(start_p);
var end_p = new google.maps.LatLng(end_lat, end_lng);
The problem is that since the call that gets the latitude and longitude is asynchronous, the code below doesn't wait to get the values before it tries to use them. They show up as undefined. I tried putting the second half of the code in its own function and calling that at the end of the longitude request, but that only worked if the longitude call happened to finish first. I also tried $.ajax({ async:false}) but that didn't do anything. This is my first time dealing with AJAX, so I'm really not sure which way to go.
For the "handler" code, use a callback instead:
function getLatLng(loc, callback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': loc}, function postcodesearch(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
callback(lat, lng);
}
}
}
getLatLng(function(lat, lng) {
alert("DO REST");
var start_p = new google.maps.LatLng(lat, lng);
});
If you need to make two calls to the geocoder, then you can always nest those calls, and put the callback after both are complete. Something like:
function getLatLng(locStart, locEnd, callback) {
geocoder.geocode({ }, function(results1) {
geocoder.geocode({ }, function(results2) {
callback(results1.lat, results1.lng, results2.lat, results2.lng);
});
});
}
getLatLng(loc1, loc2, function(lat1, lng1, lat2, lng2) {
});
use global flag variables
for example:
var flag_lat = var flag_lnt = 0;
then add in your postcodesearch functions flag_lat=1; and flag_lng=1; respectively
and in the end of each postcodesearch function check
if (flag_lat && flag_lng)
{
do_the_things_function();
flag_lat = flag_lng = 0; //reset the flags
}

Return Multiple Values From javascript function giving Error in Google Maps V3

What I want to do is that I need to create markers from stored location of user. So for that I need latitude and longitude. I got the lat & lon in my function get_current_user_lat_lon . Now I want to return both lat & lon through Object but my return is not working....
function initialize(){
var var_get_current_user_lat_lon = get_current_user_lat_lon();
var latitutde = var_get_current_user_lat_lon.latitutde;
alert(latitutde);// not even alert
var longitutde = var_get_current_user_lat_lon.longitutde;
alert(longitutde); // not even alert
}
function get_current_user_lat_lon(){
var address = $("#hidden_current_location").val();//Working fine
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var variable = results[0].geometry.location;
var lat = variable.lat();
var lon = variable.lng();
alert(lat); //Working fine
alert(lon); //Working fine
//return not working here
}
//return not working here
});
return {latitutde: lat , longitutde : lon};// giving error lat.lon is not defined means return not working here
}
Your "lat" and "lon" variables are declared inside the callback from "geocode()". Even if you declared them outside it, however, the overall idea would not work. The "geocode()" function is asynchronous; that's the reason there's a callback function in the first place.
Instead of structuring your code so that your "get_current_user_lat_lon()" function returns a value, follow the lead of the Google architecture and make your own function take a callback:
function get_current_user_lat_lon( callback ){
var address = $("#hidden_current_location").val();//Working fine
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var variable = results[0].geometry.location;
var lat = variable.lat();
var lon = variable.lng();
callback({latitude: lat, longitude: lon});
}
});
}

Categories