How to get the lat and lng of dragged waypoint - google-maps

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.

Related

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

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.

Find out distance between two points using Google map API based on medium (Road,Air,Ship)? [duplicate]

I have used the google map API to plot a way point on google map
I referred to the the following page:
https://developers.google.com/maps/documentation/javascript/directions
'Using Waypoints in Routes section' and modified it a bit so as to plot only 3 points on the map.
The following is my javascript code.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var initialloc = new google.maps.LatLng(12.971599, 77.594563);
var mapOptions = {
zoom : 6,
mapTypeId : google.maps.MapTypeId.ROADMAP,
center : initialloc
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var lat = new Array();
var lon = new Array();
var start = new google.maps.LatLng(12.971599,77.594563);
var mid = new google.maps.LatLng(12.971558,77.594552);
var end = new google.maps.LatLng(12.971558,77.594552);
var waypts = [];
waypts.push( {
location : mid,
stopover : true
});
var request = {
origin : start,
destination : end,
waypoints : waypts,
optimizeWaypoints : true,
travelMode : google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(
request,
function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
which works perfectly fine if the 3 locations are within same country, ie they have a road map.
My question is how to plot the map when the location are in different continents eg India and Australia?
Can anyone please help.
Thanks in Advance.
The problem is not about different continents, but whether the routing engine's database has information about all the countries between your start and endpoints, including car ferries. You can see that the same occurs in maps.google.com . Here's an intercontinental route from Europe to India, but if you try to move the B marker to the US or Canada, it doesn't get a route because it doesn't know a ferry across the Atlantic.
You can see what countries have coverage in this spreadsheet.

How to load markers from XML file with directions API in Google Maps

I'm trying to load markers from XML file on a map used for outputing directions. Basically, it's the combination of two demos found on Google's documentation pages.
Directions: https://google-developers.appspot.com/maps/documentation/javascript/examples/directions-panel
XML: http://gmaps-samples-v3.googlecode.com/svn/trunk/xmlparsing/downloadurl_info.html
I have first created the directions map and then tried to add XML file that contains markers.
I'm probably making a simple mistake, but since I'm not good with js and coding, can't find what. There are no errors displayed, only a blank page.
Here is my current code:
<script>
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
var control = document.getElementById('control');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP].push(control);
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("http://gmaps-samples-v3.googlecode.com/svn/trunk/xmlparsing/moredata.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(markers[i].getAttribute("name"), latlng);
}
});
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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here is the (non-working) jsFiddle: http://jsfiddle.net/ajJ3u/
Problems from a quick review:
you are creating the map twice.
you don't have a createMarker function. If that call came from one of the examples, you missed bringing it to the new map.
downloadUrl is subject to a cross-domain security restriction. If your page is not running in the "http://gmaps-samples-v3.googlecode.com" domain, it won't work. You need to access xml from the same domain as the page is running in or use a proxy.
Example of directions from/to markers from xml (translated to v3 from Mike Williams' v2 tutorial

Google Maps Waypoints not showing up

I am new to the Google Maps API and so far I have run into many issues.
I am trying to map waypoints from latlng coords determined by an array of checkboxes.
Here is my js file in full:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var waypts = [];
var start = new google.maps.LatLng(41.850033, -87.6500523);
var end = new google.maps.LatLng(40.850033, -87.6500523);
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function calcRoute()
{
var checkboxArray = document.getElementsByName("waypoints[]");
for (var i = 0; i < checkboxArray.length; i++)
{
if (checkboxArray[i].checked)
{
var lat = parseFloat(checkboxArray[i].attributes["lat"].value);
var lng = parseFloat(checkboxArray[i].attributes["lng"].value);
waypts.push({
location: new google.maps.LatLng(lat, lng),
stopover: true
});
}
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
console.log("mapping...");
if(status == google.maps.DirectionsStatus.NOT_FOUND)
{
console.log("Could not one or more of locations");
}
});
The map shows up and "mappings..." pops in the console when the page loads. When I press the calcRoute submit button nothing happens. I have logged the lat/long and the waypt object so I know they are getting to that point but it seems the route is never recalculated, etc.
I really just need a basic demo on this but the only one I have found is which I have used for almost everything but I get no results:
Google Example Directions Waypoints
Currently your script never will show any route, because you are missing the call of directionsDisplay.setDirections() to print the route.
You also should should put the call of directionsService.route() into the calcRoute-function.
fixed code:
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var start = new google.maps.LatLng(41.850033, -87.6500523);
var end = new google.maps.LatLng(40.850033, -87.6500523);
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function calcRoute()
{
var checkboxArray = document.getElementsByName("waypoints[]");
var waypoints=[];
for (var i = 0; i < checkboxArray.length; i++)
{
if (checkboxArray[i].checked)
{
var lat = parseFloat(checkboxArray[i].attributes["lat"].value);
var lng = parseFloat(checkboxArray[i].attributes["lng"].value);
waypts.push({
location: new google.maps.LatLng(lat, lng),
stopover: true
});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if(status == google.maps.DirectionsStatus.OK)
{
//print the route
directionsDisplay.setDirections(response);
}
else
{
console.log('something went wrong',status);
}
});
}
</script>
There isn't a great deal of information about how your Javascript relates to the page HTML. But this line
var checkboxArray = document.getElementsByName("waypoints[]");
should probably be
var checkboxArray = document.getElementsByName("waypoints");
assuming that all your checkboxes have the name waypoints.
What is inside the quotes should exactly match the name of the checkbox elements, so if each checkbox has the name waypoint (because each checkbox marks a single waypoint, this is a possibility) then you should use .getElementsByName("waypoint") to find all elements which have that name.