I was wondering if anyone knew how to use the google maps api to find the midpoint of a route between two places. I dont want the geographic center but rather the midpoint along the driving distance. I am new to both Javascript and the google maps api so if you could include a demo or some code with your answer it would be very helpful. The end result would output the latitude and longitude and would represent something like what this website has: http://www.geomidpoint.com/meet/.
So far I have only calculated the geographic midpoint between certain points using the algorithm here: Calculate the center point of multiple latitude/longitude coordinate pairs
I wanted to test efficiencies between geographic center and route midpoint for some research
Example that calculates the midpoint of a route
Uses the v3 version of Mike Williams' epoly library.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var polyline = null;
var infowindow = new google.maps.InfoWindow();
function createMarker(latlng, label, html) {
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString+"<br>"+marker.getPosition().toUrlValue(6));
infowindow.open(map,marker);
});
return marker;
}
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers:true});
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var travelMode = google.maps.DirectionsTravelMode.DRIVING
var request = {
origin: start,
destination: end,
travelMode: travelMode
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
polyline.setPath([]);
var bounds = new google.maps.LatLngBounds();
startLocation = new Object();
endLocation = new Object();
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
marker = createMarker(legs[i].start_location,"midpoint","","green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
computeTotalDistance(response);
} else {
alert("directions response "+status);
}
});
}
var totalDist = 0;
var totalTime = 0;
function computeTotalDistance(result) {
totalDist = 0;
totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
putMarkerOnRoute(50);
totalDist = totalDist / 1000.
document.getElementById("total").innerHTML = "total distance is: "+ totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
function putMarkerOnRoute(percentage) {
var distance = (percentage/100) * totalDist;
var time = ((percentage/100) * totalTime/60).toFixed(2);
if (!marker) {
marker = createMarker(polyline.GetPointAtDistance(distance),"time: "+time,"marker");
} else {
marker.setPosition(polyline.GetPointAtDistance(distance));
marker.setTitle("time:"+time);
}
}
code snippet:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var polyline = null;
var infowindow = new google.maps.InfoWindow();
function createMarker(latlng, label, html) {
var contentString = '<b>' + label + '</b><br>' + html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: label,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString + "<br>" + marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
});
return marker;
}
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var travelMode = google.maps.DirectionsTravelMode.DRIVING
var request = {
origin: start,
destination: end,
travelMode: travelMode
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
polyline.setPath([]);
var bounds = new google.maps.LatLngBounds();
startLocation = new Object();
endLocation = new Object();
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
marker = createMarker(legs[i].start_location, "midpoint", "", "green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
computeTotalDistance(response);
} else {
alert("directions response " + status);
}
});
}
var totalDist = 0;
var totalTime = 0;
function computeTotalDistance(result) {
totalDist = 0;
totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
putMarkerOnRoute(50);
totalDist = totalDist / 1000.
document.getElementById("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
function putMarkerOnRoute(percentage) {
var distance = (percentage / 100) * totalDist;
var time = ((percentage / 100) * totalTime / 60).toFixed(2);
if (!marker) {
marker = createMarker(polyline.GetPointAtDistance(distance), "time: " + time, "marker");
} else {
marker.setPosition(polyline.GetPointAtDistance(distance));
marker.setTitle("time:" + time);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
// from http://www.geocodezip.com/scripts/v3_epoly.js, modified to use the geometry library
// === A method which returns a GLatLng of a point a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
if (this.getPath().getLength() < 2) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += google.maps.geometry.spherical.computeDistanceBetween(this.getPath().getAt(i), this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
var p1 = this.getPath().getAt(i - 2);
var p2 = this.getPath().getAt(i - 1);
var m = (metres - olddist) / (dist - olddist);
return new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m);
}
html {
height: 100%
}
body {
height: 100%;
margin: 0px;
padding: 0px
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=geometry"></script>
<div id="tools">
start:
<input type="text" name="start" id="start" value="Hyderabad" /> end:
<input type="text" name="end" id="end" value="Bangalore" />
<input type="submit" onclick="calcRoute();" /><br />
</div>
<div id="map_canvas" style="float:left;width:70%;height:80%;"></div>
<div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<div id="total"></div>
</div>
Related
I'm using
google.maps.DirectionsRenderer({suppressMarkers: true})
to remove markers in Route. But this also removes waypoints markers in that route. So how to replace/remove 'A' and 'B' markers in a route?
Here is an example that replaces all the markers with custom markers.
Here is an example that just replaces the start and end markers with custom markers.
The custom directions renderer (renders the directions as native polylines and markers):
function RenderCustomDirections(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
waypts = [];
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
var detailsPanel = document.getElementById("direction_details");
startLocation = new Object();
endLocation = new Object();
summaryPanel.innerHTML = "";
detailsPanel.innerHTML = '<ul>';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
startLocation.marker = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
} else {
waypts[i] = new Object();
waypts[i].latlng = legs[i].start_location;
waypts[i].address = legs[i].start_address;
waypts[i].marker = createMarker(legs[i].start_location,"waypoint"+i,legs[i].start_address,"yellow");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
detailsPanel.innerHTML += "</ul>"
polyline.setMap(map);
map.fitBounds(bounds);
endLocation.marker = createMarker(endLocation.latlng,"end",endLocation.address,"red");
// == create the initial sidebar ==
makeSidebar();
} else alert(status);
}
The createMarker function:
function createMarker(latlng, label, html, color) {
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
draggable: true,
map: map,
icon: getMarkerImage(color),
shape: iconShape,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
marker.myname = label;
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
return marker;
}
custom icon function:
function getMarkerImage(iconColor) {
if ((typeof(iconColor)=="undefined") || (iconColor==null)) {
iconColor = "red";
}
if (!icons[iconColor]) {
icons[iconColor] = {
url: "mapIcons/marker_"+ iconColor +".png",
// This marker is 20 pixels wide by 34 pixels tall.
size: new google.maps.Size(20, 34),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
anchor: new google.maps.Point(9, 34));
}
return icons[iconColor];
}
I use the google maps api to draw a route in a embedded google map. I changed the color of the hole route but I also would like to change the color between the waypoints for example:
Start --orange--> firstWP --red-- > secondWP --orange--> firstWP --red--> secondWp --orange--> Destination
The color between firstWP to seceondWP should be changed but secondWP to FirstWP sould be the same color as the other parts of the route.
Furthermore I also need to move the map markers and the route should move/change
fitting to the new position of the map marker but keep the different color.
This is a minimal example with draggable map marker and changed color between waypoints but the route does not adapt to the new position of the map markers
var map;
var directionsService;
var directionsDisplay;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
suppressPolylines: true
});
calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
console.log("Entrée CALC ROUTE");
var origin = new google.maps.LatLng(origin_lat, origin_lng);
var destination = new google.maps.LatLng(destination_lat, destination_lng);
var waypointsArray = document.getElementById('waypoints').value.split("|");
var waypts = [];
for (i = 0; i < waypointsArray.length; i++) {
if (waypointsArray[i] != "") {
var waypoint = waypointsArray[i];
var waypointArray = waypoint.split(",");
var waypointLat = waypointArray[0];
var waypointLng = waypointArray[1];
console.log("waypts lat " + waypointLat);
console.log("waypts lng " + waypointLng);
waypts.push({
location: new google.maps.LatLng(waypointLat, waypointLng),
stopover: true
})
}
}
console.log("waypts " + waypts.length);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: waypts,
provideRouteAlternatives: true
};
console.log("Calc request " + JSON.stringify(request));
directionsService.route(request, customDirectionsRenderer);
}
function customDirectionsRenderer(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
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++) {
var polyline = new google.maps.Polyline({map:map, strokeColor: "blue", path:[]})
if (i == 1) {
polyline.setOptions({strokeColor: "red"});
}
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
}
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>
http://jsfiddle.net/westify/vop9o1n5/1/
Is it possible to do that? Or is it only possible if rerender the whole route after moved one waypoint?
One option would be to listen for the directions_changed event on the DirectionsRenderer, when that fires, redraw the directions polylines.
var firstTime = true;
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
console.log("directions changed firstTime=" + firstTime);
// prevent infinite loop
if (firstTime) {
google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
console.log("directions changed");
customDirectionsRenderer(directionsDisplay.getDirections(), "OK");
});
}
firstTime = !firstTime;
});
proof of concept fiddle
code snippet:
var map;
var directionsService;
var directionsDisplay;
var firstTime = true;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
suppressPolylines: true
});
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
console.log("directions changed firstTime=" + firstTime);
if (firstTime) {
google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
console.log("directions changed"); //+JSON.stringify(directionsDisplay.getDirections()));
customDirectionsRenderer(directionsDisplay.getDirections(), "OK");
});
}
firstTime = !firstTime;
});
calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
console.log("Entrée CALC ROUTE");
var origin = new google.maps.LatLng(origin_lat, origin_lng);
var destination = new google.maps.LatLng(destination_lat, destination_lng);
var waypointsArray = document.getElementById('waypoints').value.split("|");
var waypts = [];
for (i = 0; i < waypointsArray.length; i++) {
if (waypointsArray[i] != "") {
var waypoint = waypointsArray[i];
var waypointArray = waypoint.split(",");
var waypointLat = waypointArray[0];
var waypointLng = waypointArray[1];
console.log("waypts lat " + waypointLat);
console.log("waypts lng " + waypointLng);
waypts.push({
location: new google.maps.LatLng(waypointLat, waypointLng),
stopover: true
})
}
}
console.log("waypts " + waypts.length);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: waypts,
provideRouteAlternatives: true
};
console.log("Calc request " + JSON.stringify(request));
directionsService.route(request, customDirectionsRenderer);
}
var polylines = [];
function customDirectionsRenderer(response, status) {
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
polylines = [];
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
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++) {
var polyline = new google.maps.Polyline({
map: map,
strokeColor: "blue",
path: []
});
polylines.push(polyline);
if (i == 1) {
polyline.setOptions({
strokeColor: "red"
});
}
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
}
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>
I am trying to display a map to a desktop app that will have controls outside of the map that will populate certain parts of the html, and js.
What i cannot figure out is once I have a route set up, get markers on the route which would be at a distance of say 500 mile from the start.
Basically if you want to drive 500 miles where will you get. I do not want a radius from the start, but 500 miles on the route that was chosen. I have basically tried piecing together different solutions I have found online, but cannot get it to work.
I know that 1000 is not going to = 500 miles, I am just trying to get anything to work.
here is what I have:
var side_bar_html = "";
var gmarkers = [];
var map = null;
var startLocation = null;
var endLocation = null;
var length;
function initialize() {
var center = new google.maps.LatLng(24.7756, 121.0062);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: center,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var directionsService = new google.maps.DirectionsService();
var request = {
origin: "%start%",
destination: "%end%",
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
var polyline = new google.maps.Polyline({
path: [],
strokeColor: 'green',
strokeWeight: 3
});
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
var detailsPanel = document.getElementById("direction_details");
startLocation = new Object();
endLocation = new Object();
summaryPanel.innerHTML = "";
detailsPanel.innerHTML = '<ul>';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
detailsPanel.innerHTML += "<li>"+steps[j].instructions;
var dist_dur = "";
if (steps[j].distance && steps[j].distance.text) dist_dur += " "+steps[j].distance.text;
if (steps[j].duration && steps[j].duration.text) dist_dur += " "+steps[j].duration.text;
if (dist_dur != "") {
detailsPanel.innerHTML += "("+dist_dur+")<br /></li>";
} else {
detailsPanel.innerHTML += "</li>";
}
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
length = google.maps.geometry.spherical.computeLength(polyline.getPath());
detailsPanel.innerHTML += "</ul>";
polyline.setMap(map);
map.fitBounds(bounds);
createMarker(endLocation.latlng, "end", endLocation.address, "red");
// == create the initial sidebar ==
makeSidebar();
}
}
}
});
var i = 1;
var remainingDist = length;
while (remainingDist > 0) {
createMarker( polyline.GetPointAtDistance(1000 * i), i + " km", "stuff", "green" );
remainingDist -= 1000;
i++;
}
}
var icons = new Array();
icons["red"] = new google.maps.MarkerImage(
"",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 20),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34)
);
function getMarkerImage(iconColor) {
if ((typeof(iconColor) == "undefined") || (iconColor == null)) {
iconColor = "red";
}
if (!icons[iconColor]) {
icons[iconColor] = new google.maps.MarkerImage(
"",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 20),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
new google.maps.Point(9, 34)
);
}
return icons[iconColor];
}
var iconImage = new google.maps.MarkerImage(
'',
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 20),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34)
);
var iconShadow = new google.maps.MarkerImage(
'http://www.google.com/mapfiles/shadow50.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 34),
new google.maps.Point(0, 0),
new google.maps.Point(9, 34)
);
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
type: 'poly'
};
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(map, latlng, title) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: title
});
}
function createMarker(latlng, label, html, color) {
var contentString = '<b>' + label + '</b><br>' + html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: iconShadow,
icon: getMarkerImage(color),
shape: iconShape,
title: label,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
marker.myname = label;
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
// == rebuilds the sidebar to match the markers currently displayed ==
function makeSidebar() {
var html = "";
for (var i = 0; i < gmarkers.length; i++) {
html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>';
}
document.getElementById("side_bar").innerHTML = html;
}
I am new to AJAX and JavaScript so please forgive me if I am acting stupid but I am trying to pass the variable routeMid to the php page processing.php(preferable automatically one routeMid has been calculated) I tried out this code but it breaks the entire webpage. I attached the snippet with the ajax part I am having trouble with and the php code on the next page so any help would be greatly appreciated. Thanks again in advance!
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type ="text/javascript" src="http://www.geocodezip.com/scripts/v3_epoly.js"></script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var polyline = null;
var infowindow = new google.maps.InfoWindow();
var addresses = <?php echo json_encode($addresses); ?>;
function createMarker(latlng, label, html) {
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString+"<br>"+marker.getPosition().toUrlValue(6));
infowindow.open(map,marker);
});
return marker;
}
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers:true});
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = addresses[0];
var end = addresses[1];
var travelMode = google.maps.DirectionsTravelMode.DRIVING
var request = {
origin: start,
destination: end,
travelMode: travelMode
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
polyline.setPath([]);
var bounds = new google.maps.LatLngBounds();
startLocation = new Object();
endLocation = new Object();
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
marker = createMarker(legs[i].start_location,"midpoint","","green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
computeTotalDistance(response);
} else {
alert("directions response "+status);
}
});
}
var totalDist = 0;
var totalTime = 0;
function computeTotalDistance(result) {
totalDist = 0;
totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
putMarkerOnRoute(50);
var routeMid = putMarkerOnRoute(50);
document.getElementById("hiddenVal").value = routeMid;
$(".clickable").click(function() {
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'processing.php',
data: { value : routeMid }
});
});
});
totalDist = totalDist / 1000.
}
function putMarkerOnRoute(percentage) {
var distance = (percentage/100) * totalDist;
var time = ((percentage/100) * totalTime/60).toFixed(2);
var routeMidpoint;
if (!marker) {
marker = createMarker(polyline.GetPointAtDistance(distance),"time: "+time,"marker");
routeMidpoint = polyline.GetPointAtDistance(distance);
} else {
marker.setPosition(polyline.GetPointAtDistance(distance));
marker.setTitle("time:"+time);
routeMidpoint = polyline.GetPointAtDistance(distance);
}
return routeMidpoint;
}
</script>
processing.php
<?php
echo $_POST["value"];
?>
I think this is what you are trying to accomplish:
$(document).ready(function() {
function computeTotalDistance() {
totalDist = 0;
totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
putMarkerOnRoute(50);
var routeMid = putMarkerOnRoute(50);
document.getElementById("hiddenVal").value = routeMid;
$.ajax({
type: "POST",
url: 'processing.php',
data: { value : routeMid },
success:function(result){
alert("returned from php page: " + result);
}
});
totalDist = totalDist / 1000.
}
});
And then you can do what you want with the ajax result. I'm not sure what you are trying to accomplish with the click(). If you are trying to call the above function then this will work:
$(".clickable").click(function() {
computeTotalDistance();
});
I'm using
google.maps.DirectionsRenderer({suppressMarkers: true})
to remove markers in Route. But this also removes waypoints markers in that route. So how to replace/remove 'A' and 'B' markers in a route?
Here is an example that replaces all the markers with custom markers.
Here is an example that just replaces the start and end markers with custom markers.
The custom directions renderer (renders the directions as native polylines and markers):
function RenderCustomDirections(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
waypts = [];
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
var detailsPanel = document.getElementById("direction_details");
startLocation = new Object();
endLocation = new Object();
summaryPanel.innerHTML = "";
detailsPanel.innerHTML = '<ul>';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
startLocation.marker = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
} else {
waypts[i] = new Object();
waypts[i].latlng = legs[i].start_location;
waypts[i].address = legs[i].start_address;
waypts[i].marker = createMarker(legs[i].start_location,"waypoint"+i,legs[i].start_address,"yellow");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
detailsPanel.innerHTML += "</ul>"
polyline.setMap(map);
map.fitBounds(bounds);
endLocation.marker = createMarker(endLocation.latlng,"end",endLocation.address,"red");
// == create the initial sidebar ==
makeSidebar();
} else alert(status);
}
The createMarker function:
function createMarker(latlng, label, html, color) {
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
draggable: true,
map: map,
icon: getMarkerImage(color),
shape: iconShape,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
marker.myname = label;
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
return marker;
}
custom icon function:
function getMarkerImage(iconColor) {
if ((typeof(iconColor)=="undefined") || (iconColor==null)) {
iconColor = "red";
}
if (!icons[iconColor]) {
icons[iconColor] = {
url: "mapIcons/marker_"+ iconColor +".png",
// This marker is 20 pixels wide by 34 pixels tall.
size: new google.maps.Size(20, 34),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
anchor: new google.maps.Point(9, 34));
}
return icons[iconColor];
}