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();
});
Related
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 have the blinking circle from the jsfiddle link
http://jsfiddle.net/Muthukumaru/n4d80zLd/
I want to use that blinking circle in my google map based on lat/long or by location set by default.
Please find the code below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title> DIRECTIONS </title>
<style>
html{height:100%;}
body{height:100%;margin:0px;font-family: Helvetica,Arial;}
</style>
<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 map;
var directionDisplay;
var directionsService;
var stepDisplay;
var position;
var marker = [];
var polyline = [];
var poly2 = [];
var poly = null;
var startLocation = [];
var endLocation = [];
var timerHandle = [];
var speed = 0.000005, wait = 1;
var infowindow = null;
var myPano;
var panoClient;
var nextPanoId;
var startLoc = new Array();
startLoc[0] = 'Madipakkam, Chennai';
startLoc[1] = 'Koyambedu';
startLoc[2] = 'Express Avenue, Chennai';
var endLoc = new Array();
endLoc[0] = 'Express Avenue, Chennai';
endLoc[1] = 'Express Avenue, Chennai';
endLoc[2] = 'Koyambedu';
var Colors = ["#FF0000", "#00FF00", "#0000FF"];
function initialize() {
infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var myOptions = {
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
address = 'Chennai'
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
map.fitBounds(results[0].geometry.viewport);
});
// setRoutes();
}
function createMarker(latlng, label, html) {
//alert("createMarker("+latlng+","+label+","+html+","+color+")");
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,
icon:"car.png"
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
return marker;
}
function setRoutes(){
var directionsDisplay = new Array();
for (var i=0; i< startLoc.length; i++){
var rendererOptions = {
map: map,
suppressMarkers : true,
preserveViewport: true
}
directionsService = new google.maps.DirectionsService();
var travelMode = google.maps.DirectionsTravelMode.DRIVING;
var request = {
origin: startLoc[i],
destination: endLoc[i],
travelMode: travelMode
};
directionsService.route(request,makeRouteCallback(i,directionsDisplay[i]));
}
function makeRouteCallback(routeNum,disp){
if (polyline[routeNum] && (polyline[routeNum].getMap() != null)) {
startAnimation(routeNum);
return;
}
return function(response, status){
if (status == google.maps.DirectionsStatus.OK){
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
startLocation[routeNum] = new Object();
endLocation[routeNum] = new Object();
polyline[routeNum] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 1
});
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
disp = new google.maps.DirectionsRenderer(rendererOptions);
disp.setMap(map);
disp.setDirections(response);
//Markers
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation[routeNum].latlng = legs[i].start_location;
startLocation[routeNum].address = legs[i].start_address;
//marker = google.maps.Marker({map:map,position: startLocation.latlng});
marker[routeNum] = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation[routeNum].latlng = legs[i].end_location;
endLocation[routeNum].address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline[routeNum].getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
}
}
}
}
polyline[routeNum].setMap(map);
//map.fitBounds(bounds);
startAnimation(routeNum);
} // else alert("Directions request failed: "+status);
}
}
var lastVertex = 1;
var stepnum=0;
var step = 50; // 5; // metres
var tick = 100; // milliseconds
var eol= [];
//----------------------------------------------------------------------
function updatePoly(i,d) {
// Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
if (poly2[i].getPath().getLength() > 20) {
poly2[i]=new google.maps.Polyline([polyline[i].getPath().getAt(lastVertex-1)]);
//map.addOverlay(poly2)
}
if (polyline[i].GetIndexAtDistance(d) < lastVertex+2) {
if (poly2[i].getPath().getLength()>1) {
poly2[i].getPath().removeAt(poly2[i].getPath().getLength()-1)
}
poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),polyline[i].GetPointAtDistance(d));
} else {
poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),endLocation[i].latlng);
}
}
//----------------------------------------------------------------------------
function animate(index,d) {
if (d>eol[index]) {
marker[index].setPosition(endLocation[index].latlng);
return;
}
var p = polyline[index].GetPointAtDistance(d);
//map.panTo(p);
marker[index].setPosition(p);
updatePoly(index,d);
timerHandle[index] = setTimeout("animate("+index+","+(d+step)+")", tick);
}
//-------------------------------------------------------------------------
function startAnimation(index) {
if (timerHandle[index]) clearTimeout(timerHandle[index]);
eol[index]=polyline[index].Distance();
map.setCenter(polyline[index].getPath().getAt(0));
poly2[index] = new google.maps.Polyline({path: [polyline[index].getPath().getAt(0)], strokeColor:"#FFFF00", strokeWeight:3});
timerHandle[index] = setTimeout("animate("+index+",50)",2000); // Allow time for the initial map display
}
//----------------------------------------------------------------------------
</script>
</head>
<body onload="initialize()">
<div id="tools">
<button onclick="setRoutes();">Start</button>
</div>
<div id="map_canvas" style="width:100%;height:100%;"></div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-162157-1";
urchinTracker();
</script>
</body>
</html>
The above code is for multiple marker moving at a time , based on lat/long.
Thanks in advance guys.
I hope you all are doing just fine.
I have a little problem when creating a route on google maps:
I create polygons dinamically from information stored in a database and I want an alert to be shown when the route I create passes by the polygon.
The problem is that no markers are generated inside the polygon, therefore no alert is shown, so I want to know if there is walkaround for this.
This is the code I use:
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&v=3.exp&signed_in=true"></script>
<script>
var posiciones;
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
var polys = new Array();
var resultado;
var routCoordinates;
var respuesta;
var myPolygons = [
<asp:Repeater ID='rptMarkers' runat='server'>
<ItemTemplate>
{
"name": '<%# Eval("carajo") %>',
"coordinates": [
'<%# Eval("poligono1") %>',
'<%# Eval("poligono2") %>',
'<%# Eval("poligono3") %>',
'<%# Eval("poligono4") %>'
]
}
</ItemTemplate>
<SeparatorTemplate>
,
</SeparatorTemplate>
</asp:Repeater>
];
function drawPolygon(poly, polyLabel) {
var options = {
paths: poly,
strokeColor: '#AA2143',
strokeOpacity: 1,
strokeWeight: 2,
fillColor: "#FF6600",
fillOpacity: 0.7,
polyTitle: polyLabel
};
newPoly = new google.maps.Polygon(options);
newPoly.setMap(map);
polys.push(newPoly);
}
function sendPolygonForDrawing() {
for (var i = 0; i < myPolygons.length; i++) {
poly = new Array();
var coord = myPolygons[i].coordinates;
var lng = coord.length;
for (var j = 0; j < lng; j++) {
var longit_Latid = coord[j].split(',');
poly.push(new google.maps.LatLng(parseFloat(longit_Latid[0]), parseFloat(longit_Latid[1])));
}
drawPolygon(poly, myPolygons[i].name);
poly.pop();
}
}
var trucka = new google.maps.LatLng(21.984797, -102.27668);
function initialize() {
var mapOptions = {
zoom: 12,
center: trucka
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
//directionsDisplay.setPanel(document.getElementById('directionsPanel'));
directionsDisplay.setPanel(document.getElementById('hola'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
}
function fncRouteZoneIntersection(response) {
//var myRoute = response.routes[0].legs[1];
var myRoute = response.routes[0].overview_path;
var lngLatCordinates = new Array();
// for (var i = 0; i < myRoute.steps.length; i++) {
for (var i = 0; i < myRoute.length; i++) {
var marker = new google.maps.Marker({
map: map,
// position: myRoute.steps[i].start_point
position: myRoute[i]
});
// lngLatCordinates.push(myRoute.steps[i].start_point);
lngLatCordinates.push(myRoute[i]);
}
return lngLatCordinates;
}
function calcRoute() {
sendPolygonForDrawing();
var lat = document.getElementById('hdnLatitudOrigen').value;
var lon = document.getElementById('hdnLongitudOrigen').value;
var request = {
origin: new google.maps.LatLng(lat, lon),
destination: new google.maps.LatLng(document.getElementById('hdnLatitudDestino').value, document.getElementById('hdnLongitudDestino').value),
waypoints: [
{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada1').value, document.getElementById('hdnLongitudParada1').value) }
/*{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada2').value, document.getElementById('hdnLongitudParada2').value) },
{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada3').value, document.getElementById('hdnLongitudParada3').value) },
{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada4').value, document.getElementById('hdnLongitudParada4').value) },
{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada5').value, document.getElementById('hdnLongitudParada5').value) }*/
],
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives: true,
avoidHighways: false,
avoidTolls: false
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
respuesta = response;
var routCoordinates = fncRouteZoneIntersection(response);//this function populates the routCoordinates with the JSON data of the route.
var exist = new Array();
for (var i = 0; i < polys.length; i++) {//polys holds all polygons objects.
for (var j = 0; j < routCoordinates.length; j++){
// if (google.maps.geometry.poly.containsLocation(new google.maps.LatLng(routCoordinates[j].k, routCoordinates[j].A), polys[i]) == true){
if (google.maps.geometry.poly.containsLocation(routCoordinates[j], polys[i]) == true) {
//alert('CARAJO!');
alert(polys[i].polyTitle);
exist.push(polys[i].polyTitle);
break;
/*this breaks the loop checking when a point is found inside a polygon
and go check the next one, because knowing that one point of the route is
inside a polygon is enough*/
}
}
}
google.maps.event.addListener(directionsDisplay, 'directions_changed', updateInfo);
updateInfo();
}
});
}
function calcularPaso(){
var tolo = fncRouteZoneIntersection(respuesta);
var existe = new Array();
for (var i = 0; i < polys.length; i++) {
for (var j = 0; j < tolo.length; j++) {
if (google.maps.geometry.poly.containsLocation(tolo[j], polys[i]) == true) {
//alert('simon');
}
}
}
}
function updateInfo() {
//alert('carajo')
posiciones = '';
var route = directionsDisplay.getDirections().routes[0];
// var routes = response.routes;
var points = route.overview_path;
var ul = document.getElementById("vertex");
var elems = ul.getElementsByTagName("li")
for (var i = 0; i < elems.length; i++) {
elems[i].parentNode.removeChild(elems[i]);
}
for (var i = 0; i < points.length; i++) {
var li = document.createElement('li');
li.innerHTML = getLiText(points[i]);
ul.appendChild(li);
posiciones = posiciones + getLiText(points[i]);
}
document.getElementById("txtResultado").value = posiciones;
//document.getElementById("hdnResultado").value = posiciones;
calcularPaso();
}
function getLiText(point) {
var lat = point.lat(),
lng = point.lng();
return "2 " + lng + "," + lat;
return lat + ",2 " + lng + ",";
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
<div id="map-canvas" style="width: 100%; height: 400px"></div>
<div id="hola">
<label>Puntos</label>
<ul id="vertex" runat="server"></ul>
</div>
<div id="directionsPanel" style="width: 30%; height: 600px;">
<p>
Total Distance: <span id="total"></span>
</p>
</div>
On the image I am sending, you can see the polygon colored in yellow.
Hope you can help.
Thanks!
You can use [containsLocation(point:LatLng, polygon:Polygon)][1] method in the geometry library. You can use this to find whether a given point falls within a polygon, pass the point and the polygon to google.maps.geometry.poly.containsLocation(). The functions returns true if the point is within the polygon or on its edge.
https://developers.google.com/maps/documentation/javascript/geometry#containsLocation
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>
I am using the Google Distance Matrix https://developers.google.com/maps/documentation/distancematrix/
to calculate some delivery charges. When it outputs the results in the for loop it puts them onto a new line each time, so I end up with :
1
25
26
1
Is it possible to store each result in a variable so I can call each individual result elsewhere in the code for some maths to work out costs etc, so.....
$result1
$result2
$result3
$result4
As later on I would like to do things like result1 * result3 = etc etc.
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var base = new google.maps.LatLng(55.930385, -3.118425);
var start = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var end = new google.maps.LatLng(55.930385, -3.118425);
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
geocoder = new google.maps.Geocoder();
calculateDistances();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [base],
destinations: [start, end],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '<table border="1">';
deleteOverlays();
var stringArray = ['$runinPickup','$runinDestination'];
var htmlString = '<table border="1">';
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
htmlString += '<tr><td>'+stringArray[j]+'</td><td>' + results[j].distance.text +'</td></tr>';
outputDiv.innerHTML += '<tr><td>'+stringArray[j]+'</td><td>' + results[j].distance.text +'</td></tr>';
}
}
htmlString += '</table>';
// outputDiv.innerHTML += '</table>';
outputDiv.innerHTML = htmlString;
// alert(htmlString);
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
Well that shouldn't be too hard. Where you output the value, e.g.
htmlString += '<tr><td>'+stringArray[j]+'</td><td>' + results[j].distance.text +'</td></tr>';
Simply add an additional line assigning that value into a variable. I'd be inclined to add them into an array which you can loop over later.
arrResults.push(results[j].distance.text);
If you're confident you always know what each value will be, then you can simply refer to them like arrResults[0] * arrResults[2]