Asynchronous Call not working in Coffee Script - google-maps

I am using CoffeeScript, Backbone.js and Google Maps API to reverse geocode a lat / lng
I have the function
country: (origin, callback) ->
#geocoder = new google.maps.Geocoder
#geocoder.geocode(
'latLng': origin,
(results, status) =>
if status is google.maps.GeocoderStatus.OK
callback(result[6])
else alert("Geocode was not successful for the following reason: " + status);
)
When I call this I use:
#country(origin, (data) =>
console.log(data.formatted_address)
)
btw:
origin = new google.maps.LatLng(origin_lat, origin_lng)
This does not work, it does not even seem to call it. I have the call back function under (data) but can not get it to work...
Thanks

Not sure about the overall context of your question, but I will take a stab at it anyway.
The way you've defined your country function, it will typically be part of an object or map. If you just want a standalone function, try:
country = (origin, callback) ->
...
Then when calling it, try to replace #country(...) with country(...).
Based on the comments, your call to geocode also looks wrong. You need to create an instance of GeocoderRequest and pass it instead of the 'latLng': origin pair. Unfortunately I haven't used the Google style APIs much, so if this is your real question I'm not much use to you.

Related

Google maps api fastest route around traffic

I have a SPA that I need to be able to provide the user directions between two points. I want the directions to work that same way that they do currently on the web version of google maps. IE. https://www.google.ca/maps/dir/ in the hosted by google web version when you request directions it will give you the fastest route considering traffic... (See Screenshot)
Currently when I issue the request using the following code it only returns a single route that does not consider traffic.
var directionsService = this.get('directionsService');
var directionsDisplay = this.get('directionsDisplay');
directionsService.route({
origin: new google.maps.LatLng(this.get('currentLocation.lat'),this.get('currentLocation.lng')),
destination: new google.maps.LatLng(toAddress.lat,toAddress.lng),
travelMode: 'DRIVING',
provideRouteAlternatives: true
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
Does anyone know thr correct way to do this?
Check number of routes returned by DirectionService.route, the callback will have a DirectionsResult object with an array of DirectionsRoute, which contains the information about the legs and steps its composed.
If its only returning 1 route, try to set provideRouteAlternatives to true in your DirectionsRequest object.
Happy coding!
TyBourque.
I think current google map API doesn't support direction map with traffic layer.
It is only available using embedded map API.
If you have already found the best solution (not using embedded map API), please write here
Regards

google maps reverse geocoding: passing variables

I am trying to get store the address correspoding to a latitude,longitude in a variable (in javascript). I created a call back function (after reading numerous posts on it) and the code is as follows. Now I want to store the address in a variable called location3.
Oddly enough, for an alert right after location3 is assigned, it is undefined. But if it is looked at 300ms later, then it gives the right value. I want to get the address assigned to location3 immediately. Any suggestions are welcome.
function codeLatLng1(lat,long,callback) {
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat,long);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
callback(results[1].formatted_address);
myvariable=results[1].formatted_address;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
lat1_last=37;long1_last=-100;
codeLatLng1(lat1_last,long1_last,function(locat) {location3=locat;});
alert (location3); // THIS ALERT SHOWS THAT IT IS STILL UNDEFINED
setTimeout(function(){alert (location3);},300); // THIS ALERT GIVES THE RIGHT ADDRESS
The idea to grasp here is that the 2nd argument to geocode(), a callback function, is not going to be called right away, but rather only after a result is received from Google. Meanwhile, the function codeLatLng1(), having posted the request, returns control to the caller. In your program, that means the first alert() happens next, followed by some wait time during which Google gets back to you, the callback is called, and so on.
Likewise, your anonymous callback that sets location3 is only executed when that result is received - not before codeLatLng1 returns.
It would make more sense to put your alert inside your anonymous callback. Typically this is where final processing of the result goes.
This is an example of asynchronous or event-driven programming.
I hope this makes it clear!

Geolocation HTML5 enableHighAccuracy True , False or Best Option?

i have a problem about HTML5 geolocation feature. I use the code below to get location data. I use "enableHighAccuracy: false" option to work with Cell Based GPS feature. Accurancy is low but response it too fast. But some people always use Built-in GPS with their mobile phone, so this code does not work for them. Bu if i change accurency option as "enableHighAccuracy: true" it works for them. But this time, the code uses only built-in GPS. not CELL based GPS.
The question -> How can i do that : First, try to get position from Built-in GPS with timeout (e.g. 5000ms ) if position cannot be got in this time just look for Cell Based position for timeout (e.g. 10000ms) if position cannot be get in this time, return an error message .
Here is the code that i use now.
Thanks in advance.
function getLocationfromGoogle() {
navigator.geolocation.getCurrentPosition(
function(pos) {
$("#lat_field").val(pos.coords.latitude);
$("#long_field").val(pos.coords.longitude);
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(pos.coords.latitude,pos.coords.longitude);
geocoder.geocode({ 'latLng': latLng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//console.log(results[0].formatted_address);
$("#adresim").val(results[0].formatted_address);
}
else {
alert('Google convertion is not succesfully done.');
}
});
},function error(msg){
alert('Please enable your GPS position future.');
},{maximumAge:600000, timeout:5000, enableHighAccuracy: false}
);
}
You should also be aware that the implementation of this varies from phone OS to phone OS - what works on Android may or may not work on iOS, BlackBerry, WindowsPhone, etc.
You're almost there, you just need to:
Specify enableHighAccuracy: true (you have it set to false)
Handle the timeout error case in the error handler. If the error from the high accuracy query is timeout, then try it again with enableHighAccuracy: false.
Have a look at this sample code.
You should also note that when testing this on a few devices, it returns location derived from WiFi even when enableHighAccuracy: true.
The code mentioned here: http://jsfiddle.net/CvSW4/ did not work for me during error handling.
The reason is that the error functions accept a parameter named 'position' but use an object in the functions called 'error'.
function errorCallback_highAccuracy(position) { ... }
function errorCallback_lowAccuracy(position) { ... }
The solution to fix this was to switch the error methods to accept the input value as a parameter named 'error' and not 'position', since the error callbacks do not accept a position and throw an error object instead.
function errorCallback_highAccuracy(error) { ... }
function errorCallback_lowAccuracy(error) { ... }
I mention it here, because I could not post on the resulting example page and also, this is the location where I linked through to find the code sample mentioned above.

Write a location and get the geocords, not working properly? JS

Link removed
This is my site. Im working on so you can enter a location on the search input field, and then see theres xx km from a restaurant.
Now i got almost everything working. If you see the source code you can see how it works. It showAddress(what you searched). And then show addresses makes it into lat/lng cords, and pass it to computeRestaurants() which computes the distances between the location you entered and the restaurants.
Somehow, when I run:
computeRestaurants(new google.maps.LatLng(55.662133, 12.508028));
outside the functions, it works and gives correct values.
But when i do:
showAddress('Valby'); // (like in the source code)
You can see that it returns NaN. And inside showAddress() it executes the same command as the one i wrote above computeRestaurants( the point )
So why will it not work properly?
point in showAddress is: (55.662133, 12.508028) so it is already converted to LatLng cords and therefore no need to new google.maps.latlng(...
My only bet right now is the brackets () ??
replace your showAddress by this:
var geocoder;
function showAddress(address)
{
if (typeof(geocoder) == 'undefined') geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
computeRestaurants(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
You are using mixup of v2 and v3 apis, and that is the problem.

Google Maps V3 Route Destination Mark Edit

Using the google.maps.DirectionsService.route() and google.maps.DirectionsRenderer.setDirections() method, is it possible to change the text on the info window for the destination, without creating a custom parser for the journey?
I couldn't see anything in the API which allowed you to access the markers of the route.
I don't want any code, just yes/no, and a hint for the right direction to take.
Current Function:
var request = {
origin: origPoint,
destination: new google.maps.LatLng(dest.lat(), dest.lng()),
travelMode: google.maps.DirectionsTravelMode.DRIVING,
region: "GB"
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
Thanks,
Psy
I'm afraid that the api doesn't offer a direct way to access the info windows or access the markers.
But there are several ways to achieve that parsing parts of the result data:
I guess the simplest way to change text on the info window is to overwrite the DirectionsLegs' start and/or end addresses of the DirectionsResult. You have to do it before calling directionsDisplay.setDirections(result).
Or you can display just the polyline (see suppressMarkers and suppressInfoWindows of renderer's options) and create the markers and infowindows yourself - you have to access data from DirectionsLegs of DirectionsResult.
I would prefer the second way since it's cleaner and you have more freedom in adjustments. The first way, it's only a hack and you are just changing the text.