Google Maps API: ZERO RESULTS or INVALID REQUEST while drawing routes - javascript

I am trying to draw a route based on the co-ordinates that i receive from the database. But somehow i am not able to draw. I either get ZERO RESULTS or INVALID REQUEST.. The route i am trying to draw is a TRANSIT ROUTE. Where as i found some similar issues(Link) being addressed in the site but the solution given was to add departure time or arrival time in the parameters. And it was an accepted answer. The same which i tried is not working currently. I have posted the code that i have tried.
Below are the co-ordinates:
19.1860640243063 72.9759523272514
19.1902699 73.023094
19.2178474133021 73.086293040406
19.2354157727173 73.1302742969937
Please help.
load : function(response)
{
for(var i=0;i<response.length;i++)
{
if(response[i].linkData!='undefined')
{
link=response[i].linkData;
var lastPos=(response.length-1);
linkDes=response[lastPos].linkData;
var linkDes=link.split(" ");
var linkValue=link.split(" ");
var latDes= parseFloat(linkDes[0]);
var longDes= parseFloat(linkDes[1]);
var lat = parseFloat(linkValue[0]); //convert string to float
var lon = parseFloat(linkValue[1]); //convert string to float
if(count==0)
{
var source=new google.maps.LatLng(lat, lon);
count++;
}
if(i!=0 )
{
geoLatLong=new google.maps.LatLng(lat, lon);
count++;
}
if(i!=response.length-1)
{
geoLatLong=new google.maps.LatLng(lat, lon);
}
if(latDes!="" && longDes!="")
{
var destination=new google.maps.LatLng(latDes, longDes);
}
if(count>1 && count<=response.length-1)
{
geoLatLongArray.push(geoLatLong);
}
}
}
for(var i=0;i<geoLatLongArray.length;i++)
{
waypts.push({location:geoLatLongArray[i],stopover:true});
}
var request = {
origin: source,
destination: destination,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
transitOptions:
{
departureTime: new Date()
}
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
alert("directions response "+status);
}
});
}

According to v3 API Docs
google.maps.TravelMode.TRANSIT
is the correct syntax.

I had similar issue. I fixed it after making origin to an address field (instead of coordinates). this issue persists only when both origin and destination are coordinates.
You can perhaps convert your coordinates into address using Reverse Geocode API and then pass the converted addresses to origin / destination.

Related

Remove rendered direction routes on google map

I try to render direction route on google map and my issue was, when I am try to get another direction route previously rendered route not clear. I want to know how I reset rendered route on the map.
Here my code.
function direction(dest, lat, lng) {
$('#direction').slideUp();
$('#results').slideDown();
$('#dest-direction').val(dest);
$('#direction-form').submit(function () {
var ori = $('#origin-direction').val();
map.setZoom(7);
var currentLatLng = new google.maps.LatLng(lat, lng);
map.setCenter(currentLatLng);
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsRenderer.setPanel(document.getElementById('direction'));
var directionsService = new google.maps.DirectionsService();
/////////////////////
default_unit_system = google.maps.UnitSystem.METRIC;
if (current_unit == "km") {
default_unit_system = google.maps.UnitSystem.METRIC;
} else if (current_unit == "miles") {
default_unit_system = google.maps.UnitSystem.IMPERIAL;
}
/////////////////////
var request = {
origin: ori,
destination: lat+','+lng,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: default_unit_system
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(response);
} else {
//alert('Error: ' + status);
$('#direction').append('<table width="100%"><tr><td>Direction not found. Please try again.</td></tr></table>');
}
});
$('#direction-form').nextAll().remove();
return false;
});
}
I agree with Dr.Molle .
Still, One thing that can be useful for many overlays (like markers, like infowindows, ...): Store the objects in an array;
if needed, keep that array on the global scope;
then you can easily remove them from the map.
var renderObjects = [];
function clearRenderObjects() {
for(var i in renderObjects) {
renderObjects[i].setMap(null);
}
}
$('#direction-form').submit(function () {
// clear previous
clearRenderObjects();
...
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
// add to the array
renderObjects.push(directionsRenderer);
...
});
Use the same DirectionsRenderer-instance for all requests(currently you create a new instance on each request)

Google Maps API, Setting a name of marker when getting directions

I have a program that allows the user to select multiple items for a trip. Part of the program maps the items in google maps. I am using the lat/long coordinates to generate the waypoints and then the API takes it from there. The final map shows the route and markers. I would like to give each marker a custom name instead of the default street address currently being displayed. Is this possible?
//Display the route on the map
$.post("processors/getMapWayPoints.php",{
tripID: tripID
}, function(e){
console.log("Return is " + e);
latlong = JSON.parse(e);
//iterate through each locations lat/long and add it to the mappoints array for the route plotting
for(var i = 0; i < latlong.length; i+=3){
var name = latlong[i];
var lat = latlong[i+1];
var lng = latlong[i+2];
//create google lat/long point object
var pt = new google.maps.LatLng(lat, lng);
//add the location to the array for the route
mappoints.push({location:pt, stopover:true});
//not being used yet
pointNames.push(name);
}
var mapOptions = {
zoom:11,
center: home
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
var request = {
origin:home,
destination:home,
waypoints: mappoints,
//optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
});

How to wait for Direction Service to complete to access Direction property of Direction Display

I'm doing my work with Google Map API. To draw a route between two points, I use this function:
function calcRoute(start, end) {
var pStart = new google.maps.LatLng(start.lat(), start.lng());
var pEnd = new google.maps.LatLng(end.lat(), end.lng());
var request = {
origin: pStart,
destination: pEnd,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
// Box the overview path of the first route
var path = result.routes[0].overview_path;
boxes = rboxer.box(path, distance);
//drawBoxes(boxes);
nearbyMarkets = search_market(boxes);
// PUT HERE???
}
});
}
After this, I need access the Direction Display object, which only available after the route is rendered successfully (means this function's done). I tried to put that code block in that position, but at that time, the Direction property of Direction Display is still not available, so it's failed. But if I call it after calcRoute function, it's OK.
So, my question is, how can I know when the callback finish so that I can continue my work? I've tried putting a flag like below, but it was unsuccessful, the loop is infinite.
function calcRoute(start, end) {
var pStart = new google.maps.LatLng(start.lat(), start.lng());
var pEnd = new google.maps.LatLng(end.lat(), end.lng());
var pass = false;
var request = {
origin: pStart,
destination: pEnd,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
// Box the overview path of the first route
var path = result.routes[0].overview_path;
boxes = rboxer.box(path, distance);
//drawBoxes(boxes);
nearbyMarkets = search_market(boxes);
pass = true;
}
});
while (!pass) {
}
}
Observe the directions_changed-event:
google.maps.event.addListener(directionsDisplay, 'directions_changed',function(){
if(this.get('directions')){
//directions are available, do something
}
});

Google Maps Api check if place is on the route

I made with Google Maps an route between two places. Thats works fine.
But i also have an database with interesting points on different roads in
my country. I like to show them if they are on the generated route. Places who are
not one this route, don't need to be shown.
My database with intereseting points contains latitude and longitude coordinates.
How can i check is they are on my route? There are approximately 30 or 40 interesting
point in my database.
// set request
var request = {
origin: initialLocation,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
// make route
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// set route
directionsDisplay.setDirections(response);
}
});
UPDATE:
Build new function "isLocationOnEdge". But the check runs the markers when they are not on the road:
// get flitsers on the route
function getFlitsersOnRoute(){
// set request
var request = {
origin: current_location,
destination: $('#gegevens').html(),
travelMode: google.maps.TravelMode.DRIVING
};
// make route
directionsService.route(request, function(response, status) {
// isLocationOnEdge
var isLocationOnEdge = google.maps.geometry.poly.isLocationOnEdge;
var coords = response.routes[0].overview_path;
var image = base_url+'external/afbeeldingen/google_markers/flitser.png';
// get flitsers
$.ajax({
type: "POST",
async:false,
url: base_url+"advies/get/9",
success: function (data) {
var result = jQuery.parseJSON(data);
// loop trough flitsers
$.each(result.flitsers.m, function(i, item) {
// latitude longitude
var latlng = item["#attributes"].gps.split(",");
// make google latlng
var myLatlng = new google.maps.LatLng(latlng[0],latlng[1]);
if (myLatlng,coords)
{
// set and define the marker
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
size: new google.maps.Size(15, 15),
icon: image,
title: 'Flitser'
});
}
});
}
});
});
}
isLocationOnEdge(point:LatLng, poly:Polygon|Polyline, tolerance?:number)
To determine whether a point falls on or near a polyline, or on or near the edge of a polygon, pass the point, the polyline/polygon, and optionally a tolerance value in degrees to google.maps.geometry.poly.isLocationOnEdge(). The function returns true if the distance between the point and the closest point on the line or edge falls within the specified tolerance. The default tolerance value is 10-9 degrees.
https://developers.google.com/maps/documentation/javascript/geometry
Include the geometry library in your Google Maps API request:
http://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry&sensor=TRUE_OR_FALSE
Pseudo-code:
// Make isLocationOnEdge easier to access
var isLocationOnEdge = google.maps.geometry.poly.isLocationOnEdge;
for (var i = 0; i < interestingPlaces.length; i++) {
if (isLocationOnEdge(interestingPlaces[i],
response.routes[0].overview_path))
{
// Do something with interestingPlaces[i]
}
}
Google maps documentation for isLocationOnEdge()

Using waypoints to find the route

I am working on finding the route between two points using javascript, google maps api v3 and pgoruting. Now I have the following method which works fine when I give just one waypoint. BUT it does not work when I jave more than one waypoint. The format when there is more than one waypoint is delimeted with this symbol '|'. Therefore for example: 36.762121,14.7866553|35.988777778,14.655444333
The javascript method is the following:
function calcRoute() {
var all_nodes = document.getElementById('result').innerHTML;
var node = all_nodes.split("|");
var start = node[0];
var end = node[node.length - 1];
var wpts = [];
for (var i = 1; i < node.length-1; i++) {
wpts.push({
location:node[i],
stopover:true
});
}
var request = {
origin: start,
destination: end,
waypoints: wpts,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
alert('No route found');
}
});
}
Actual thats incorrect waypoints are arrays of location:LatLng and stopover:true or false and they do not use the pipe delimiter please refer to Waypoints
As previously suggested, it might help to get a google object for the location and it may also help to supply the lat and long as two seperate entities.
for (var i = 1; i < node.length-1; i = i + 1) {
node[i] = node[i].split(',');
wpts.push({
location:new google.maps.LatLng(node[i][0], node[i][1]),
stopover:true
});
}

Categories