Javascript skipping lines when trying to geocode location - javascript

I'm trying to use this function to geocode a string passed to it into a google maps result.
function codeAddress(address) {
var firstResult;
geocoder.geocode( { 'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
firstResult = results[0];
} else {
firstResult = "failed";
}
});
return firstResult;
}
The problem is that when I try to debug it using the debugger from chrome and insert a breakpoint outside and inside the ceocoder.geocode statement, I can clearly see the program execution go at the third line, but it skips the inner lines and goes straight to the return value (returning an undefined value). Some other times, it goes through the if statement within it, but it doesn't go to the return statement although I have set up a breakpoint there.
Am I trying to do this the wrong way? How can I fix this?

I found some possible answers on StackOverflow, they might help:
Aleem Saadullah on SO posted:
Finally figured it out. It was a silly error. I had linked my Javascript file before linking the jQuery. The code works fine now.
Mikko Ohtamaa answered on SO:
To be strict, whatever custom CGI you are using does not conform
JavaScript syntax.
What I suggest is that you make your custom dynamic processing into
JavaScript comments, so that it doesn't affect the normal JavaScript
parsing. This is much easier than writing your custom JavaScript
parser to cater your custom syntax.
E.g.
// %import and other custom commands here
The best approach is that you would not put any non-JavaScript to JS
files at all. If you need importing and such there are some more
generic JavaScript solutions for them.
http://browserify.org/
http://requirejs.org/
EDIT 2:
Found an answer on Engineer's answer on SO:
geocoder.geocode works asynchronously, so you need to wait until its
response will be delivered from google's servers, and only then use
responded data. Put your loop inside of callback:
geocoder.geocode( { 'address': zip }, function(results, status) { // status is empty
if (status == google.maps.GeocoderStatus.OK) {
var userLat = results[0].geometry.location.lat();
var userLng = results[0].geometry.location.lng();
userLatLng = results[0].geometry.location;
for (var i = data.length-1; i--;) {
//loop body
}
}});//end geocode

Related

Google maps api, gecode. Trying to geocode a language specific address

I'm sure this question has been asked somewhere, but for the life of me i can't seem to find it..
I have an address in "København S" denmark, that i am trying to geocode so i can place a marker on my map. However i get the zero results error, and i can see that
"København S"
has been changed to
"København S"
with the hex.
I'm sure this is fairly easy to get around, but i have been trying the past hour and i think im making it to complicated for myself. Is there an easy workaround to specify the character set i want it to use rather than it being in partly hex?
Here is my code, the error msg and the msg with the hex.
function geocodeAddress() {
var geocoder = new google.maps.Geocoder();
if (geoIndex < addressesToGeo.length) {
var addressSplit = addressesToGeo[geoIndex].split("SPLIT"); // temp
alert(addressSplit[0]); // second alert msg image
geocoder.geocode({ 'address': addressSplit[0] }, makeCallBack(parseInt(addressSplit[1])));
++geoIndex;
}
else {
clearInterval(geoTimer);
}
}

Delete/move Google maps marker (jquery-ui-maps)

I want to remove one marker from my Google Map, but I can't seem to get it to work. I find various answers, all telling me to use .setMap(null) on the marker, but I can't seem to get it to work.
$map_canvas = $('#map_canvas');
var youreHere_Marker;
function centerMapToAddress( address ) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if( typeof youreHere_Marker!=="undefined"){
youreHere_Marker.setMap(null);
}
youreHere_Marker = $map_canvas.gmap('addMarker', {'position': results[0].geometry.location.lat()+','+results[0].geometry.location.lng(), 'bounds': true});
}
});
}
I get TypeError: youreHere_Marker.setMap is not a function. To my knowledge this means that the variable youreHere_Marker doesn't have the method .setMap(), but if I do console.log(youreHere_Marker) and inspect the object, I can see the method.
I have more markers on my map, via the MarkerClusterer. Those should remain untouched
I have the feeling I'm close, could someone point me in the right direction?
Edit: I've also tried .setPosition(), same error. I'm assuming I'm using the variable incorrect, but I don't know how to refer to it properly.
Well, i was working with google maps without jQuery, but i think (i'm not sure, but you may try) that you should get your marker with the following code:
youreHere_Marker = $map_canvas.gmap('get', 'markers')[0];
youreHere_Marker.setMap(null);
I'm really not sure that it will do what you want, but there is a possibility that this will work : )
I hope you'll solve you problems.
Thanks. : )

Javascript promise on google elevation service

I'm still pretty new with the Promise implementations in javascript. Although I got an easy example working, it didn't work after I popped the Google API elevation callback function in. I would very much appreciate if someone could help me with the function please, because I intend to use this approach a number of times in my application.
this is my current Promise function code (as defined in a javascript class structure):
LinkClass.prototype.getElev = function(coordinate)
{
return new Promise(function(resolve,reject)
{
//get User elevation again, because it is possible that the user elevation did not lock
var locations = []; //locations array
locations.push(coordinate);
// Create a LocationElevationRequest object using the array's one value
var positionalRequest = {'locations': locations}
//get User elevation for antenna elevation calculation
var elevator = new google.maps.ElevationService();
elevator.getElevationForLocations(positionalRequest, function(results, status)
{
if (status == google.maps.ElevationStatus.OK)
{
// Retrieve the first result
if (results[0])
{
resolve(results[0].elevation.toString());
}
else
reject('No valid result was determined from the Google Elevation service. Please try again');
}
else
reject('Google Elevation service was not available. Please try again');
});
}); //end of promise function
}
And then where I implement the function:
LinkClass.prototype.drawLine = function()
{
//do other stuff...
this.getElev(this.UserLocation).then(function(response){
//for now just print the result
alert(response);
},function(Errortxt){
alert(Errortxt);
});
//do other stuff
}
I really need to get this working please!
Thanks
Completely forgot to post the answer for this question. Thanks again for the inputs. For what it's worth, my code posted here is correct for implementing promises, and really cool if you want to synchronize and use answers from callback functions... For all practical purposes, this will work by default in the majority of browsers without including external "Promise javascript" files or whatever, except for Internet Explorer. (They should shortly start to notice that their browser development skills are becoming extinct).
Here is link to standard promise implementation, which I used, with minimum browser version support :) Promise browser impl & support

Is there a way to use the Google Maps TimeZone API from within the google.maps object

So in order to look for places you can use the Google Places API you can either use the API like this
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AddYourOwnKeyHere
or you could use the functionality inside the google.maps object like this
service = new google.maps.places.PlacesService(this.gmap);
var that = this;
if ( data.search.length <= 0 ) {
request['types'] = data.types;
service.nearbySearch(request, function(results, status) {
that.markPlaces(results, status);
that.gmap.setZoom(14);
});
} else {
request['query'] = data.search;
service.textSearch(request, function(results, status) {
that.markPlaces(results, status);
that.gmap.setZoom(14);
});
}
I was wondering if there is a built in object inside the google.maps object to use the instead of the API, just like the Places Service
https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510&timestamp=1331161200&key=API_KEY
The reason I'm asking is because IE8 is giving me a hard time with the ajax request (cross-domain) and I'd like to not rely on the XDomain object built in IE8

Google maps direction service sends different response formats

I am using javascript, google direction service
I have multiple source points on the map and one destination point. I need to find the closest source point to the destination point. As direction service works asynchronously I need to map points with their lat/lang. However the problem is that, the response format sent by direction service changes.
function calcRoute(start, end) {
var request = {
origin:start,
destination:end,
travelMode:google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request,
function (response, status) {
distanceCount++;
if (status == google.maps.DirectionsStatus.OK) {
var dist = computeTotalDistance(response);
console.log(dist);
if (dist < minDistance) {
minDistance = dist;
minDistanceIndex = locationsMap[response.ug.origin.Ua+""+response.ug.origin.Va];
}
if (distanceCount == vl.length) {
drawWay(vl[minDistanceIndex], fsl);
}
}
}
);
}
The problem occurs on the line
minDistanceIndex = locationsMap[response.ug.origin.Ua+""+response.ug.origin.Va];
response.ug.origin.Va and response.ug.origin.Ua comes from google direction service, however it sometimes changes to response.ug.origin.Xa and response.ug.origin.Ya.
Do you have any ideas why it changes from time to time? or any ideas how to deal with that problem?
You don't have to access those internal properties, they are not a part of the API so they may change.
Use only the properties/methods defined inside the specification, all data provided by the response are accessible through them,
example:
response.routes[0].legs[0].start_location
//returns latLng of the origin
Apart from that:
Your description sounds as if you better should use a DistanceMatrixRequest

Categories

Resources