google maps JavaScript issues - javascript

First off thank you in advance for taking time to help me with this, I appreciate your efforts.
I have a problem with google maps api, JavaScript version 3.
I have written the following code
$('.adr').ready(function(){
initialize();
})
function initialize() {
var myLatlng = codeAddress();
var myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
}
function codeAddress()
{
var geocoder = new google.maps.Geocoder();
var address;
var street = cropAdr($(".street-address").text());
var city = cropAdr($(".locality").text());
var state = cropAdr($(".region").text());
var zip = cropAdr($(".zip").text());
address = street + ", " + city + ", " + state + ", " + zip;
geocoder.geocode( {'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var latlng = results[0].geometry.location;
return latlng;
}
else
{
alert("Geocode was not successful for the following reason: " + status);
return null;
}
});
}
function cropAdr(args)
{
var index = args.indexOf(":");
var value = args.substr(index+1);
return value;
}
But it doesn't work.
I have checked the value of the "results[0].geometry.location" return and its perfect, so the address manipulation works. The "results[0].geometry.location" is a google.maps.Latlng object, but I have tried to strip out just the co-ords as strings, then create a new google.maps.Latlng object but no dice.
yet if I manually copy that string and paste the value into "var myLatlng = new google.maps.Latlng(Paste Copied String here!)" the whole thing works!!
I cannot see what else is wrong this script (apologies for the jumble of Jquery and Javascritpt).

The Google Maps API Geocoder accepts a function that will be run when the address has been geocoded, but that function may be called asynchronously - that is, after the rest of your code has already finished running.
In codeAddress you call the Geocoder and pass in a function with this line:
geocoder.geocode( {'address': address}, function(results, status)
You then try and return a latLng from the function passed to the geocoder, but that is not the same as returning a value from codeAddress. The value you return from inside this function will be passed to the geocoder object, which will just ignore it.
You need to have the function you pass to geocode do something with the latLng. For example, replace:
return latLng;
with:
map.setCenter(latLng);
And the map should center itself on the geocoded address once the result is available.
(To do this you will need to make the map object global or otherwise make it available to codeAddress. I suggest adding "var map;" at the top of your code, and remove "var" from in front of the use of map in initialize)

Related

aJax request, wait for it to complete

im using the Google API, i want to make it that there can be multiple addresses marked on the map so im using the Geocoder. However the rest of my code is running before this Geocoder returns the result it seems!
// Handle addresses
var addressesHandled = [];
function handleAddresses(addressObj) {
for (i = 0; i < addressObj.length; i++) {
addressesHandled[i] = new Address(addressObj[i]['title'], addressObj[i]['address'], addressObj[i]['latlng'], addressObj[i]['defaultOpen']);
}
}
// Address object
function Address(title, address, latlng, defaultOpen) {
this.title = title;
this.address = address;
this.latlng = latlng;
if (latlng == undefined) {
this.latlng = codeAddress(address);
}
this.defaultOpen = defaultOpen;
}
As you can see im going through each object and getting the address if the lat and lng values are undefined. If these are undefined I then execute the codeAddress function which will get the lat and lng values from the current address, however I think that the rest of the script is still running whilst this happens!
Below is the codeAddress function, I thought I was unable to the return the result however now I believe that it simply isn't being returns quick enough.
How can I fix this issue so the rest of my script waits until each address has had it's lat and lng calculated!?
function codeAddress(address, callback) {
var geocoder;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var loc = [];
// loc = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
loc[0] = results[0].geometry.location.lat(); loc[1] = results[0].geometry.location.lng();
console.log(loc);
callback(loc);
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
Edit:
Hmm, I just thought would it be easier just to process the marker and add it to the map as each geocode function has it's result returned ?

Google Maps API - results.geometry.location[0] returning null

fairly new to javascript and trying to make a simple map application. I am trying to center a new map around an address that is passed through a function. The issue I have is it is always being returned null which I do not understand, do I have to specify return types in the function format?
My code:
<script>
var geocoder;
var map;
function initialize() {
var address = document.getElementById('address').value;
var latlng = GetLatLong(address);
alert(latlng);
var mapOptions = {
zoom: 8,
center: latlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function GetLatLong(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location)
return results[0].geometry.location;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I have a div for the address text and a div for the map location. To debug I put alert("") in some places to see the order in which it gets called on runtime, why would the line I put the first alert be called before the function is called?
Thanks
The Google Maps API call that you are performing is asynchronous. In layman's terms that means that as soon as you start the call, the rest of your program keeps executing independent of it. It is essentially running to the side of the rest of your program. The purpose of the function that you pass to the geocoder call is to deal with the data that the call returns asynchronously.
You would need to change your code to do something like this:
function initialize() {
var address = document.getElementById('address').value;
GetLatLong(address);
}
var map;
function GetLatLong(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location)
var latlng = results[0].geometry.location;
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}

Google Maps API and JavaScript Issues :-(

Ive been working on a Google Maps application and have hit a hurdle due to a lack of knowledge in js me thinks?!
So... here's my JSON object
{"pickuppoint0":"LE9 8GB","pickuppoint1":"LE2 0QA","pickuppoint2":"LE3 6AF","pickuppoint3":"LE2 8GB","pickuppoint4":"LE8 8TE","pickuppoint5":"LE2 2GB","pickuppoint6":"LE1 6AF"}
And here's a loop through the JSON object...
$.each(alltravelgroups, function(k, v){
for(var i=0; i < boxes.length; i++){
var bounds = boxes[i];
if(bounds.contains(getLatLng(v))){
alert("im here");
}
}
});
And here's my getLatLng() method I've created...
function getLatLng(pickuppoint) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': pickuppoint}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return results[0].geometry.location
} else {
alert('getLatLng Geocode was not successful for the following reason: ' + status);
}
});
}
Now... what I'm trying to do is simply take the value from each key/value pair and produce a LatLng object that can then be used within the "bounds.contains()" method for searching within the bounds box provided by the RouteBoxer class.
The problem I'm facing is the value returned by the getLatLng method is "undefined" when using alert(getLatLng(v)) and should just be a 'location' containing both latitude and longitde? Anyone able to point what I'm doing wrong?
Please refer the link below.
http://jsfiddle.net/y829C/13/
var mapOptions = {
center: new google.maps.LatLng(-33.8665433, 151.1956316),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
In the above code, semicolon is missing in return results[0].geometry.location.

Convert latitude, longitude in to address as a string

Please help me resolve this problem.
I want to get address from latitude, longitude in Google Maps.
Here is my functions:
function codeLatLng() {
var geocoder = new google.maps.Geocoder();
var lati = document.getElementById("latitude_value").value;
var lngi = document.getElementById("longitude_value").value;
var latlng = new google.maps.LatLng(lati, lngi);
var infowindow = new google.maps.InfoWindow();
var ngo;
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
ngo = results[1].formatted_address;
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
return ngo;
}
When this function is executed. The address is displayed in Maps.
However, this is not what I need. I just want to assign this address to variable 'ngo' as a string.
This function return 'ngo' which is displayed in the text field as 'undefinded'.
I need some help to solved this problem.
Thanks.
I just want to assign this address to variable 'ngo' as a string.
That's the problem right there. You can't do that. JavaScript just doesn't work that way. The geocoder call is asynchronous. It returns before the data is received from the server. The data isn't ready until the geocoder callback function is called.
What you need to do instead is to use that ngo data in the callback function itself, or call another function and pass it the data, and use the data there.
For example, where you have this line:
ngo = results[1].formatted_address;
you can replace it with:
useNGO( results[1].formatted_address );
where useNGO is a function you've defined (anywhere) like this:
function useNGO( ngo ) {
// Do stuff with ngo here
}
I believe your problem is that using the var keyword when declaring var ngo makes ngo a local variable, so it doesn't exist outside of codeLatLng(). Try deleting var ngo, placing ngo = ""; somewhere outside of any function declarations (like right before function codeLatLng() {), and let me know if that works :)

google maps geocoding and order of initialization

so I've run into a problem recently, and maybe you guys can help.
So to start off, I've created website and a marker, and I'm trying to retrieve the center point to reverse-geocode the address.
My code is below :
function ReverseGeocode(lat, lng)
{
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"latLng": latlng}, function(results, status)
{
if (status != google.maps.GeocoderStatus.OK)
{
alert("Geocoding has failed due to "+ status);
}
address = results[0].formatted_address;
});
}
The problem I'm having here, is when I try to pass "address" back out (address is right now a global variable) all I get is "undefined".
Here's the code where I'm trying to pass it back out:
sendString += '&lat=' + lat;
sendString += '&lng=' + lon;
ReverseGeocode(center.lat(), center.lng());
alert(""+address);
sendString += '&address=' + address
var currentLang = "en"
sendString += '&phone=' + document.getElementById("number").value;
sendString += '&email=' + document.getElementById("email").value;
sendString += ($("prefsms").checked)?'&contactMethod=sms':'&contactMethod=email';
sendString += '&serviceType=' + document.getElementById("serviceType").value;
sendString += '&language=' + currentLang;
alert(""+sendString);
In my alert box, all I get is "undefined". Yet, if I add another alert box INTO the ReverseGeocode function, I'll get the address in an alert box, but this occurs AFTER the alert box in the outside function.
Any ideas as to what's going on? I would have thought that the alert box inside the ReverseGeocode function would go first, not the other way around.
Thanks!
As Heitor Chang said, Geocoding is asynchronous - so when you try to return the address, it get's returned to the function you pass as a callback to geocoder.geocode(). Confused? see this:
function ReverseGeocode(lat, lng)
{
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"latLng": latlng}, function(results, status)
{
if (status != google.maps.GeocoderStatus.OK)
{
alert("Geocoding has failed due to "+ status);
}
return results[0].formatted_address; // this is how you might've been returning (i am just assuming since you didn't provide any code that returns address.
});
}
Now you can see that it gets returned to the function you are passing to geocoder.geocode()
What you should be doing is use callbacks - you are passing one here, probably without realising it - accept a callback as the third argument to ReverseGeocode function and when you get the result as OK, call the callback and return the address. Here's how:
function ReverseGeocode(lat, lng, cb) // cb - callback, a function that takes the address as an argument.
{
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"latLng": latlng}, function(results, status)
{
if (status != google.maps.GeocoderStatus.OK)
{
alert("Geocoding has failed due to "+ status);
}
cb(results[0].formatted_address); // call the callback passing to it the address and we're done.
});
}
How to use it? This way:
ReverseGeocode( LAT, LNG, function(address) {
// do something with the address here. This will be called as soon as google returns the address.
});
(Reverse) Geocoding is asynchronous, meaning the request goes to Google servers, your script keeps running, and the code inside result is OK block executes when Google sends back its reply. The overall execution won't necessarily follow the order of commands in the order it was written.
To use the value of address your code has to be included in that code block where the status returned is OK.

Categories