I'm using a simple script to geocode addresses.
var geocoder;
var departure;
var arrival;
function initialize() {
geocoder = new google.maps.Geocoder();
}
google.maps.event.addDomListener(window, 'load', initialize);
function geocode(options) {
var address = options.address.val() || null;
var result = {};
if (address) {
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result.lat = results[0].geometry.location.lat();
result.lng = results[0].geometry.location.lng();
} else {
result.lat = null;
result.lng = null;
}
});
}
}
function geocode_all() {
departure = geocode({
address: $('#departure')
});
//console.log(departure);
arrival = geocode({
address: $('#arrival')
});
//console.log(arrival);
}
I would like that my departure variable and my arrival variable to be object with the resulting latitude and longitude.
How should I proceed as my result variable is out of scope?
Thanks !
The problem isn't that the function is anonymous, and it isn't scope; the problem is that the Google geolocation API is asynchronous. It's impossible for your geocode function to return its result; instead, just like Google's function, it must accept a callback that it calls back with the result later, when the result is known. (Or it can use callbacks indirectly, via the "promise" pattern, but the fundamental concept is the same.)
So, using a callback:
function geocode(options, callback) {
// ^--- Accept the callback
var address = options.address.val() || null;
var result = {};
if (address) {
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result.lat = results[0].geometry.location.lat();
result.lng = results[0].geometry.location.lng();
} else {
result.lat = null;
result.lng = null;
}
callback(result); // <== Call it
});
}
}
// usage
geocode({/*...*/}, function(result) {
// This gets called later, asynchronously, with the result
});
Or using a jQuery Deferred/Promise:
function geocode(options) {
var d = new $.Deferred(); // <== Create the deferred
var address = options.address.val() || null;
var result = {};
if (address) {
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result.lat = results[0].geometry.location.lat();
result.lng = results[0].geometry.location.lng();
} else {
result.lat = null;
result.lng = null;
}
// Resolve the Deferred using your result
d.resolve(result);
});
}
// Return the Promise for the Deferred
return d.promise();
}
// Usage
geocode({/*....*/}).done(function(result) {
// This gets called later, asynchronously, with the result
});
Related
I have an object inside an Angular.js factory:
angular.module('myapp')
.factory('geoLocationService', function () {
var geoLocationObj = {};
var 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;
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[2]) {
geoLocationObj.resultCity = results[2].formatted_address;
alert(geoLocationObj.resultCity);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
return geoLocationObj;
});
This works alert(geoLocationObj.resultCity); and alerts in property value
But
console.log(geoLocationObj);
does not log the propety geoLocationObj.resultCity
I am trying to use geoLocationObj.resultCity outside the Factory in my controller but it is not there.
I have in my controller:
.controller('IndexCtrl', function ($scope, geoLocationService) {
var geoLocationService = geoLocationService;
console.log(geoLocationService);
geoLocationService is an empty Object
I cannot figure out why this is happening.
Can you help me with this?
The problem in your code is that your object is initialize in the callback (_successFunction) that means that the returned object is still empty because the _successFunction hasn't been called.
You should return a promise using $q and call .then() in your controller.
angular.module('myapp')
.factory('geoLocationService', ['$q', function ($q) {
var geoLocationObj = {};
var deferred = $q.defer();
var 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;
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[2]) {
deferred.resolve(results[2].formatted_address);
alert(geoLocationObj.resultCity);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
return deferred.promise;
})];
And in your controller
.controller('IndexCtrl', function ($scope, geoLocationService) {
geoLocationService.then(function(geoLocObj){
console.log(geoLocObj); Here your object has been resolved
});
Your factory should return something like this
angular.module('myapp')
.factory('geoLocationService', function() {
return{
geoLocationObj:function(){
var 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;
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[2]) {
geoLocationObj.resultCity = results[2].formatted_address;
alert(geoLocationObj.resultCity);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
return geoLocationObj
}
}
});
You can call in your controller like this
angular.module('myapp', [])
.controller('IndexCtrl', function ($scope, geoLocationService) {
var promise = geoLocationService.geoLocationObj()
promise.then(function(success){
console.log("me "+success);
},function(error){
console.log("They eat all my candies :" +error)
})
});
You can play it here in Js bin
PS. You need to include your google map libs
I am working with the google maps API and whenever I return the variable to the initialize function from the codeLatLng function it claims undefined. If I print the variable from the codeLatLng it shows up fine.
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var addr = codeLatLng();
document.write(addr);
}
function codeLatLng() {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
return results[1].formatted_address;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
prints out undefined
If I do:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
codeLatLng();
}
function codeLatLng() {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
document.write(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
prints out New York, NY 10012, USA
You can't return the value from the function, the value doesn't exist yet when the function returns.
The geocode method makes an asynchonous call and uses a callback to handle the result, so you have to do the same in the codeLatLng function:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
codeLatLng(function(addr){
alert(addr);
});
}
function codeLatLng(callback) {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
callback(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
You're making an asynchronous request, your codeLatLng() function has finished and returned long before the geocoder is done.
If you need the geocoder data to continue, you'll have to chain your functions together:
function initialize() {
geocoder = new google.maps.Geocoder();
codeLatLng();
}
function codeLatLng() {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
initContinued(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
function initContinued(addr) {
alert(addr);
}
You can get value using localstorage.
geocoder.geocode({
'address': address,
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
localStorage.setItem("endlat", latitude);
localStorage.setItem("endlng", longitude);
});
var end_lat = localStorage.getItem("endlat");
var end_lng = localStorage.getItem("endlng");
But it returns previous value.. Returns current value when we click twice...
pass geocoder as a parameter to the codeLatLng() function.
function codeLatLng(geocoder) {
call it like so in your initialize function:
var addr = codeLatLng(geocoder);
That return is not returning from codeLatLng; it's returning from the anonymous function being passed to geocoder.geocode.
I think you'll need to pass the data using another mechanism e.g. a global variable
Code:
function setMaps() {
var geocoder = new google.maps.Geocoder();
var result = "";
$('.map_canvas').each(function(){
geocoder.geocode( {
'address': $(this).attr('address'),
'region': 'de'
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result += results[0].geometry.location.lng()+",";
result += results[0].geometry.location.lat();
} else {
result = "Unable to find address: " + status;
}
$(this).gmap({ 'center': result });
});
});
}
This method should show multiple maps on one page.
HTML:
<div class="map_canvas" address="Berlin, Zoo">
</div>
The problem is that $(this).gmap({ 'center': result }); does not work:
Uncaught TypeError: Cannot set property 'position' of undefined
Any idea how to pass the map_canvas object to the callback function?
try this:
function setMaps() {
var geocoder = new google.maps.Geocoder();
var result = "";
$('.map_canvas').each(function(){
var _this = $(this); // <------ here
geocoder.geocode( {
'address': $(this).attr('address'),
'region': 'de'
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result += results[0].geometry.location.lng()+",";
result += results[0].geometry.location.lat();
} else {
result = "Unable to find address: " + status;
}
_this.gmap({ 'center': result }); // <---- and here
});
});
}
I'm trying to return the variable coord from GetLocation, but it only returns undefined.
Any help appreciated!
var coord = "";
function GetLocation(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
coord = ParseLocation(results[0].geometry.location);
// This alert shows the proper coordinates
alert(coord);
}
else{ }
});
// this alert is undefined
alert(coord);
return coord;
}
function ParseLocation(location) {
var lat = location.lat().toString().substr(0, 12);
var lng = location.lng().toString().substr(0, 12);
return lat+","+lng;
}
When you are returning coords from the outer function it is still in fact undefined. The inner function executes later when the asynchronous operation (if it wasn't asynchronous, the API would just give the result to you normally) is done.
Try passing a callback:
function GetLocation(address, cb) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
cb(ParseLocation(results[0].geometry.location));
}
else{ }
});
}
You can then use it like so:
GetLocation( "asd", function(coord){
alert(coord);
});
I'm trying to use the Google geocoder API V3 to plot a location on a map based on an address specified by the user, code is below.
When I make a request directly (e.g. to http://maps.googleapis.com/maps/api/geocode/json?address=peterborough&sensor=false) I get the expected response. However, when I make the same request using the code below, the midpoint variable is always undefined after the getLatLong function has exited.
What am I doing incorrectly?
function loadFromSearch(address)
{
midpoint = getLatLong(address);
mapCentre = midpoint;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}
function getLatLong(address)
{
var result;
var url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&sensor=false'
$.getJSON(url,
function (data){
if (data.status == "OK")
{
result = data.results[0].geometry.location;
}
});
return result;
}
==================================================================================
In light of responses, I have now updated the code to the following. I'm still not getting any result though, with breakpoints set in Firebug the result = data.results[0].geometry.location; never gets hit.
function loadFromSearch(address)
{
midpoint = getLatLong(address, loadWithMidpoint);
}
function getLatLong(address, callback)
{
var result;
var url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&sensor=false'
$.getJSON(url,{},
function (data) {
if (data.status == "OK")
{
result = data.results[0].geometry.location;
callback(result);
}
});
}
function loadWithMidpoint(centre)
{
mapCentre = centre;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}
=============================================================================
I have it! The final code, which works, looks like this:
function loadFromSearch(coordinates, address)
{
midpoint = getLatLong(address, latLongCallback);
}
function getLatLong(address, callback)
{
var geocoder = new google.maps.Geocoder();
var result = "";
geocoder.geocode({ 'address': address, 'region': 'uk' }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
result = results[0].geometry.location;
latLongCallback(result);
}
else
{
result = "Unable to find address: " + status;
}
});
return result;
}
function latLongCallback(result)
{
mapCentre = result;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}
If you are using V3 of the API cannot you use the this?
function findAddressViaGoogle() {
var address = $("input[name='property_address']").val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
newPointClicked(results[0].geometry.location)
} else {
alert("Unable to find address: " + status);
}
});
}
The above is what I use to find some lat long cordinates of an inputted address, May work better?
EDIT:
function loadFromSearch(address)
{
midpoint = getLatLong(address);
mapCentre = midpoint;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}
function getLatLong(address)
{
var geocoder = new google.maps.Geocoder();
var result = "";
geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result = results[0].geometry.location;
} else {
result = "Unable to find address: " + status;
}
});
return result;
}
The problem is your $.getJSON function is asynchronous, yet you are returning the 'result' synchronously.
You need to do something like this (not tested!)
function loadFromSearch(address)
{
midpoint = getLatLong(address, function(midpoint){
// this is a callback
mapCentre = midpoint;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
});
}
function getLatLong(address, callback)
{
var result;
var url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&sensor=false'
$.getJSON(url,
function (data) {
if (data.status == "OK") {
result = data.results[0].geometry.location;
callback(result) // need a callback to get the asynchronous request to do something useful
}
});
}
In response to your edit: Oh dear, it looks like the V3 geocoder does not support JSONP. This means you can not do a cross-domain request to get data from it in your browser. See http://blog.futtta.be/2010/04/09/no-more-jsonp-for-google-geocoding-webservice/
However Brady's solution does work. I guess that is the way Google want us to geocode now.