javascript function is returning undefined - javascript

I'm trying to implement google maps and the problem I am having is that when I call the function getLatLng, it is returning an undefined value and I can't figure out why.
initialize();
var map;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var address = "Rochester, MN";
var myLatLng = getLatLng(address);
console.log("myLatLng = "+myLatLng);
}
function getLatLng(address) {
var codedAddress;
geocoder.geocode({'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
codedAddress = results[0].geometry.location;
console.log("codedAddress 1 = "+codedAddress);
} else {
alert("There was a problem with the map");
}
console.log("codedAddress 2 = "+codedAddress);
});
console.log("codedAddress 3 = "+codedAddress);
return codedAddress;
}
In the firebug console, here is the output that I get in this exact order:
codedAddress 3 = undefined
myLatLng = undefined
codedAddress 1 = (44.0216306, -92.46989919999999)
codedAddress 2 = (44.0216306, -92.46989919999999)
Why is codedAddress 3 and myLatLng showing up first in the console?

geocode is asynchronous (i.e. it sends a request to Google's servers), so you need to pass a callback function to getLatLng, rather than having it return immediately:
function getLatLng(address, callback) {
var codedAddress;
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
codedAddress = results[0].geometry.location;
console.log("codedAddress 1 = "+codedAddress);
} else {
alert("There was a problem with the map");
}
console.log("codedAddress 2 = "+codedAddress);
callback(codedAddress);
});
}

Here's what I got to work via the Google Maps documentation:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var address = "Rochester, MN";
var latlng = codeAddress(address);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Here's a jsFiddle to see it in action. Obviously, you can update this to use jQuery if you need to.

You're missing a closing } for the initialize function.

Related

In my geocoder geocode callback, how do I determine which request the result corresponds to?

I'm looping through about 60 addresses to get them geocoded for use on a Google Map. My callback (below) seems to work well for collecting the locations, but I need to know how to relate them to the address objects I'm looping through. I can't find anything in the geocode response that tells me which of my requests it 'came from.'
Is there a way to do that?
This is my function:
geocode() {
var lv_location;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address' : this.address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// what data in results can be used to relate the location to the address?
lv_location = results[0].geometry.location;
}
markerCounter++;
if (markerCounter >= 60) finishSurnames();
});
}
In JavaScript you can use Immediately-invoked function expression that will create a function scope also known as closure. You should change your function to something similar to
geocode() {
var lv_location;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address' : this.address}, (function(originalAddress){
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// what data in results can be used to relate the location to the address?
//You can use the originalAddress variable here to relate result to request
lv_location = results[0].geometry.location;
}
markerCounter++;
if (markerCounter >= 60) finishSurnames();
};
})(this.address));
}
}
Have a look at my example, it geocodes 3 addresses and print in console result and corresponding request string
var addresses = [
'av Diagonal 197, Barcelona',
'av Lucas Vega 53, San Cristobal de La Laguna',
'Metrologichna 14, Kiev'
];
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
addresses.forEach( function(address) {
geocode(geocoder, address);
});
}
function geocode(geocoder, address) {
geocoder.geocode({'address': address}, (function(originalAddress) {
return function(results, status) {
if (status === 'OK') {
console.log("Search: " + originalAddress + "->" + results[0].geometry.location.toString());
} else {
console.log("Search: " + originalAddress + "->" + status);
}
};
})(address));
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap">
</script>
I hope this helps!

How to get current location name from longitude and latitude?

I'm using this code to get the current location of the user through google maps api and i am getting the location in the form of latitude and longitudes and getting the location in LatLng variable.
But after that when I am converting the latitude and longitude to an address then its not working.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (p){
var LatLng = new google.maps.LatLng(p.coords.latitude,p.coords.longitude);
alert(LatLng);
alert(p.coords.latitude);
alert(p.coords.longitude);
var mapOptions = {
center: LatLng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'LatLng': LatLng }, function (results, status){
alert(geocoder);
if (status == google.maps.GeocoderStatus.OK){
if (results[1]){
alert("Location: " + results[1].formatted_address);
}
}
});
Firstly as the commentator Parker told, jsp and java tags are irrelevant for your post. I removed it.
You should do the reverse geocoding. The process of doing the converse, translating a location on the map into a human-readable address, is known as reverse geocoding.
Please refer the below google map url for Reverse Geocoding.
See the below snippet of mapping lat & lan to location,
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
Let me know if it helps.
$(document).ready(function() {
var currgeocoder;
//Set geo location of lat and long
navigator.geolocation.getCurrentPosition(function(position, html5Error) {
geo_loc = processGeolocationResult(position);
currLatLong = geo_loc.split(",");
initializeCurrent(currLatLong[0], currLatLong[1]);
});
//Get geo location result
function processGeolocationResult(position) {
html5Lat = position.coords.latitude; //Get latitude
html5Lon = position.coords.longitude; //Get longitude
html5TimeStamp = position.timestamp; //Get timestamp
html5Accuracy = position.coords.accuracy; //Get accuracy in meters
return (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
}
//Check value is present or not & call google api function
function initializeCurrent(latcurr, longcurr) {
currgeocoder = new google.maps.Geocoder();
console.log(latcurr + "-- ######## --" + longcurr);
if (latcurr != '' && longcurr != '') {
var myLatlng = new google.maps.LatLng(latcurr, longcurr);
return getCurrentAddress(myLatlng);
}
}
//Get current address
function getCurrentAddress(location) {
currgeocoder.geocode({
'location': location
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0]);
$("#address").html(results[0].formatted_address);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
});
</script>

Google Maps API doesn't display map if the center is populated by a javascript function

So, when I do this:
<!-- javascript file -->
function geocodeFromAdress(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
console.log(latLng.lat() + ", " + latLng.lng());
return latLng.lat() + ", " + latLng.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
<!-- HTML view -->
<script type="text/javascript">
$(function(){
myOptions = {
center: new google.maps.LatLng(geocodeFromAdress('Los Angeles')),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Gmaps.map = new google.maps.Map($('.map')[0], myOptions);
addFacilities(Gmaps.map);
});
</script>
the map is not rendered, but if I do:
<script type="text/javascript">
$(function(){
myOptions = {
center: new google.maps.LatLng(34.0522342, -118.2436849),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Gmaps.map = new google.maps.Map($('.map')[0], myOptions);
addFacilities(Gmaps.map);
});
</script>
then the maps is properly rendered. Why it doesn't accept the coordinations from the JS function?
The output of the JS function: 34.0522342, -118.2436849
Thank you in advance.
The map does not reder beacause center in mapOptions need a value but when you made this:
center: new google.maps.LatLng(geocodeFromAdress('Los Angeles'))
the return from geocodeFromAdress('Los Angeles') is undefined, so there is no value to pass to google.maps.LatLng function.
You can give a center temporarly and then set the center when the geocoder returns :
function geocodeFromAdress(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
console.log(latLng.lat() + ", " + latLng.lng());
Gmaps.map.setCenter(latLng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Or initialize the map when geocoder returns :
function geocodeFromAdress(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
console.log(latLng.lat() + ", " + latLng.lng());
myOptions = {
center: new google.maps.LatLng(latLng),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Gmaps.map = new google.maps.Map($('.map')[0], myOptions);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

Helper function of a controller does not return anything

I have a function in my map controller to convert an address to a google.maps.latlng and I want to return this value, but my function doesn't return anything. I think thats because the values change inside another function, but I can't figure out how to solve this.
addressToLatLng: function(address) {
var geocoder = new google.maps.Geocoder(), lat, lng, latlng;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
latlng = new google.maps.LatLng(lat, lng);
console.log(latlng); // will give me the object in the log
}
});
return latlng; // nothing happens
},
That's because the geocode call is asynchronous, so you are trying to return the value before it exists.
You can use a callback for the caller to get the value when it arrives:
addressToLatLng: function(address, callback) {
var geocoder = new google.maps.Geocoder(), lat, lng, latlng;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
latlng = new google.maps.LatLng(lat, lng);
callback(latlng);
}
});
},
Usage:
yourController.addressToLatLng(address, function(latlng){
console.log(latlng);
});

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);
}
}
}
});
}

Categories