routes are not defined when calling calcRoute with params (latLng) - Google Maps - google-maps

I need to call pass params to calcRoute() on click, what I am doing is:
function calcRoute(source,destt) {
var start = new google.maps.LatLng(source);
var end = new google.maps.LatLng(destt);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
Click Event:
$('#go').click(function(){
var from= "24.942834,67.121237";
var to = "24.944908,67.124491";
calcRoute(from,to);
});
It's returning the status with ZERO_RESULT
It was working fine when I hard coded lat n lng in calcRoute(), i.e
var start = new google.maps.LatLng(24.942834,67.121237);
var end = new google.maps.LatLng(24.944908,67.124491);
Thanks for any Help.

Direct string will not work as LatLng object you have to convert "24.942834,67.121237" to google.maps.LatLng to make it work.
$('#go').click(function(){
var from= new google.maps.LatLng(24.942834,67.121237);// convert it to latlng object
var to = new google.maps.LatLng(24.944908,67.124491);
calcRoute(from,to);
});
if you have "24.942834,67.121237" then you can use it like this:
var str="24.942834,67.121237";
var latlng=str.split(',')
var to = new google.maps.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));

Related

How to get the lat and lng of dragged waypoint

I am making this app where I let the user draw a waypoints route with google maps directions service and currently I am working on the edit route page - that is where the user can drag the waypoints of the route to reorder them. I am having trouble getting the lat and lng of the currently dragged waypoint.
How can I access the lat/lng of the dragged waypoint object on drag end?
This is my code:
<script type="text/javascript">
var rendererOptions = {
draggable: true
};
var phpway = <?php echo json_encode($phpway); ?>;
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
var waypts = [];
for(var i = 0; i < phpway.length; i+=2){
waypts.push(new google.maps.LatLng(Number(phpway[i]), Number(phpway[i+1])));
}
var start = waypts[0];
var end = waypts[waypts.length-1];
var mywaypts = [];
var pointsArray = [];
for (var i = 1; i < waypts.length-1; i++) {
mywaypts.push({
location:waypts[i],
stopover:true});
}
var australia = new google.maps.LatLng(-25.274398, 133.775136);
function initialize() {
var mapOptions = {
zoom: 7,
center: australia
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
//computeTotalDistance(directionsDisplay.getDirections());
calcRoute();
});
calcRoute();
}
function calcRoute() {
console.log(start);
var request = {
origin: start,
destination: end,
waypoints: mywaypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
In the 'directions_changed' event handler, process through the "new" directions returned from:
directionsDisplay.getDirections(). The start/end locations of each leg are the waypoints (note that the end of the first leg will be the same point as the start of the second).
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
document.getElementById('waypoints').innerHTML = "";
var response = directionsDisplay.getDirections();
var route = response.routes[0];
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
document.getElementById('waypoints').innerHTML += legs[i].start_location.toUrlValue(6) +":";
document.getElementById('waypoints').innerHTML += legs[i].end_location.toUrlValue(6)+"<br>";
}
});
fiddle
Inspect var dirs = directionsDisplay.getDirections();, maybe using console.log(dirs); to get a glance at the request format.
You will find the origin under dirs.request.origin, the destination under dirs.request.destination and the waypoints under dirs.request.waypoints.
To find the waypoint you have just ended dragging, keep the previous request (there should always be one, even before the first drag, since you first load the the route to be edited) and search for the differences in between this previous request and the current one via a simple iteration through the 'set of waypoints'. I suspect that there should be only one difference you find between the two (no matter if you introduce a new waypoint or you move an already existing one). That is your last dragged waypoint.

Add stopover to waypoints

I am having trouble adding stopover points to my google maps route. This is my calcRoute function below. Basically I have an array of latlng objects called waypts and all the points between waypts[0] and waypts[waypts.length-1] should be stopover points. I know I just need to loop through those points and make a stopover with something like this:
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var phpway = <?php echo json_encode($phpway); ?>;
var waypts = [];
for(var i = 0; i < phpway.length; i+=2){
waypts.push(new google.maps.LatLng(phpway[i], phpway[i+1]));
}
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = waypts[0];
var end = waypts[waypts.length-1];
var mywaypts = [];
for (var i = 1; i < waypts.length-1; i++) {
mywaypts.push({
location:waypts[i],
stopover:true});
}
var request = {
origin: start,
destination: end,
waypoints: mywaypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You should not include your start/end points in your waypoints array, and just pass your waypts array in your request this way:
var request = {
origin : start,
destination : end,
waypoints: waypts,
travelMode : google.maps.TravelMode.DRIVING
};
See doc: https://developers.google.com/maps/documentation/javascript/directions?hl=FR#Waypoints

Can we draw custom routes on Google maps?

I am exploring Google maps APIs. I have a web service which returns the GeoJSON object in response. I want to render it on the Google maps. I tried below API;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
This gives us the GeoJSON for given start and end in request parameter. I am trying to get the GeoJSON response from my service and instead of Google data, I am trying to render my own response.
The data returned from my custom service is in the same format as Google.
The data returned from Google service is in the form like
I have constructed the object same is Google DirectionsService Response.
Please check details below;
https://developers.google.com/maps/documentation/javascript/directions#DirectionsResults
"routes":[{"bounds":{"northeast":{"lat":30.2844454,"lng":-97.7040698},"southwest":{"lat":30.2121885,"lng":-97.7506593}},"copyrights":"Map
data ©2014 Google","legs":.... Steps....}
EDIT:
I tried another option with addGeoJson() API as;
function loadGeoJsonString(geoString) {
var geojson = JSON.parse(geoString);
map.data.addGeoJson(geojson);
zoom(map);
}
JSON string which I am using is validated by jsonlint.
Something like this?
directionsDisplay = new google.maps.DirectionsRenderer();
var Basingstoke = new google.maps.LatLng(51.2949612, -1.0643864);
var mapOptions = {
zoom:7,
center: Basingstoke
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
var point1 = new google.maps.LatLng(51.2941293,-0.9139252);
var point2 = new google.maps.LatLng(51.3250339,-0.8050919);
var wps = [{ location: point1 }, { location: point2 }];
var org = new google.maps.LatLng ( 51.2949612, -1.0643864);
var dest = new google.maps.LatLng ( 52.3069282, -0.7540226);
var request = {
origin: org,
destination: dest,
waypoints: wps,
durationInTraffic: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var newRoute = response.routes[0].legs[2].duration.value;
directionsDisplay.setDirections(response);
alert ('Travel Time: ' + newRoute + ' seconds');
}
else
alert ('failed to get directions');
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Google Maps Directions dragged polyline coordinates reset after extending the route

Hey guys, the function of this code is described below.
there are some predefined functions below i.e getMapOption and others
function initialize(){
var divCalcDis = $('divCalcDis');
var pdist = $('pdist');
var pTimeTaken = $('pTimeTaken');
var txtLatLon = $('divLatLon');
var lblDistance = $('lblDistance');
var mapOption = mapHandler.getMapOption(that.LonLatCoordinates[0], 15, "Default");
map = mapHandler.getMap('map_canvas', mapOption);
var renderOption = { draggable: true };
directionsDisplay = new google.maps.DirectionsRenderer(renderOption);
directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () { for (i = 0; i < directionsDisplay.directions.routes.length; i++) {
//getting latlon
txtLatLon.innerHTML = "";
console.log(directionsDisplay.directions.routes[i].overview_path.length);
var latLng = directionsDisplay.directions.routes[i].overview_path[k];
var latLng = directionsDisplay.directions.routes[i].overview_path[directionsDisplay.directions.routes[i].overview_path.length - 1].toString();
latLng = latLng.split('(')[1];
latLng = latLng.split(')')[0];
latLng = latLng.split(' ');
latLng = latLng[0] + latLng[1];
txtLatLon.innerHTML += latLng;
}
});
startMap();
}
function startMap() {
var i=0;
google.maps.event.addListener(map, 'click', function (event) {
i++;
if(i === 1){
mapHandler.setMarker(event.latLng, map, "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png", null, null, null, that.permanentMarkers, false);
that.origin = event.latLng; //comma seperated values of lat,lon
}
else if(i > 1){
mapHandler.setMarker(event.latLng, map, "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png", null, null, null, that.permanentMarkers, false);
if (i === 2) {
that.dest = event.latLng; //comma seperated values of lat,lon
}
else if (i > 2) {
that.wayPTs.push({
location: that.dest,
stopover: true
});
that.dest = event.latLng;
}
that.calcRoute();
}});
};
function calcRoute() {
var divCalcDis = stringHandler._id('divCalcDis');
var pdist = stringHandler._id('pdist');
var pTimeTaken = stringHandler._id('pTimeTaken');
var txtLatLon = stringHandler._id('divLatLon');
txtLatLon.innerHTML = "";
if (!that.wayPTs.length > 1) {
this.wayPTs = null;
}
var request = this.directionsRequest(this.origin,this.dest,google.maps.DirectionsTravelMode.DRIVING,this.wayPTs,false,true,true,google.maps.DirectionsUnitSystem.METRIC);
that.directionsResponse.route(request, function (response, status) {
//console.log(response);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
};
**
I am making a project using Google Maps API V3 Directions library in which i am creating a route when a user click some place on the map
Here is a screenshot**
Now when i drag the direction drawn line it works smoothly and giving me the latitude and longitude correctly.
Here is a screenshot
But the Problem is when i click on anyother place on the map(after dragging) the waypoint refreshes and i get the old without drag route with the next stop as you can see below
Here is a Screenshot
How to save the latLon of the waypoint so they are available after creation of new points Thx
You need to push the coordinates into the route array so they will always be available. So push when you drag and push when you click. May be this can be of assistance to you. Best of luck.

Displaying multiple routes on a google map

I am trying to display multiple routes on same map but am unable to do so.
No matter what I do I get only one route.
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Any pointers will be helpful.
I had the same problem. This thread on a Google group for Google maps shows how to do it.
The author (a Google employee), wrote this:
You should be able to create two DirectionsRenderer objects, each that
use the same map and different DirectionsResults.
var map = new google.maps.Map(document.getElementById("map_canvas"));
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer;
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
}
var directionsService = new google.maps.DirectionsService;
function requestDirections(start, end) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result) {
renderDirections(result);
});
}
requestDirections('Huntsville, AL', 'Boston, MA');
requestDirections('Bakersfield, CA', 'Vancouver, BC');
I tried it and it does work.
Did you try as follows?
Here I have captured one path and displayed it. You can do the same by writing pointsArray = result.routes[1].overview_path; besides it and display it in a new loop.
directionsService.route (request, function (result, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections (result);
pointsArray = result.routes[0].overview_path;
var i = 0;
var j = 0;
for (j = 0; j < pointsArray.length; j++)
{
var point1 = new google.maps.Marker ({
position:pointsArray [j],
draggable:false,
map:map,
flat:true
});
}
}
});