How to rotation a marker Google Maps API? [duplicate] - javascript

I'd like to know if it possible to change the marker orientation according the path drawn on the map. Here is a example:
As you can see the marker is a car (with front bumper and tail lights). I'd like to orientate the car in the direction the path is going (in this exemple orientate the car around 45 degrees to the right).
I'm using DirectionsService to draw the path and I have a random number of point. Sometime only one, sometime 10 points. I'm adding the markers before drawing the paths. Here is how I'm drawing the path:
// Intialize the Path Array
var path = new google.maps.MVCArray();
// Intialise the Direction Service
var service = new google.maps.DirectionsService();
// Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: gmap, strokeColor: '#dd0000' }); // #4986E7
// Draw the path for this vehicle
for (var i = 0; i < pathPoints.length; i++) {
if ((i + 1) < pathPoints.length) {
var src = pathPoints[i];
var des = pathPoints[i + 1];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++){
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
Is it possible to do that?

One option is to translate your icon to SVG then use the Symbol rotation property to align it with the road (you can do the same with a PNG image by either making a large number of copies of the icon rotated by a degree or two, or by making a custom icon that allows you to rotate the PNG icon arbitrarily)
marker.setPosition(p);
var heading = google.maps.geometry.spherical.computeHeading(lastPosn,p);
icon.rotation = heading;
marker.setIcon(icon);
proof of concept fiddle
code snippet:
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var position;
var marker = null;
var polyline = null;
var poly2 = null;
var speed = 0.000005,
wait = 1;
var infowindow = null;
var timerHandle = null;
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);
infowindow.open(map, marker);
});
return marker;
}
function initialize() {
infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService();
// Create a map and center it on Manhattan.
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
address = 'new york';
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
map.setCenter(results[0].geometry.location);
});
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// Instantiate an info window to hold step text.
stepDisplay = new google.maps.InfoWindow();
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
poly2 = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
}
var steps = [];
function calcRoute() {
if (timerHandle) {
clearTimeout(timerHandle);
}
if (marker) {
marker.setMap(null);
}
polyline.setMap(null);
poly2.setMap(null);
directionsDisplay.setMap(null);
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
poly2 = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
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
};
// Route the directions and pass the response to a
// function to create markers for each step.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
startLocation = new Object();
endLocation = new Object();
// 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, "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;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
map.setZoom(18);
startAnimation();
}
});
}
var step = 50; // 5; // metres
var tick = 100; // milliseconds
var eol;
var k = 0;
var stepnum = 0;
var speed = "";
var lastVertex = 1;
//=============== animation functions ======================
function updatePoly(d) {
// Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
if (poly2.getPath().getLength() > 20) {
poly2 = new google.maps.Polyline([polyline.getPath().getAt(lastVertex - 1)]);
// map.addOverlay(poly2)
}
if (polyline.GetIndexAtDistance(d) < lastVertex + 2) {
if (poly2.getPath().getLength() > 1) {
poly2.getPath().removeAt(poly2.getPath().getLength() - 1);
}
poly2.getPath().insertAt(poly2.getPath().getLength(), polyline.GetPointAtDistance(d));
} else {
poly2.getPath().insertAt(poly2.getPath().getLength(), endLocation.latlng);
}
}
function animate(d) {
if (d > eol) {
map.panTo(endLocation.latlng);
marker.setPosition(endLocation.latlng);
return;
}
var p = polyline.GetPointAtDistance(d);
map.panTo(p);
var lastPosn = marker.getPosition();
marker.setPosition(p);
var heading = google.maps.geometry.spherical.computeHeading(lastPosn, p);
icon.rotation = heading;
marker.setIcon(icon);
updatePoly(d);
timerHandle = setTimeout("animate(" + (d + step) + ")", tick);
}
function startAnimation() {
eol = polyline.Distance();
map.setCenter(polyline.getPath().getAt(0));
marker = new google.maps.Marker({
position: polyline.getPath().getAt(0),
map: map,
icon: icon
});
poly2 = new google.maps.Polyline({
path: [polyline.getPath().getAt(0)],
strokeColor: "#0000FF",
strokeWeight: 10
});
// map.addOverlay(poly2);
setTimeout("animate(50)", 2000); // Allow time for the initial map display
}
google.maps.event.addDomListener(window, 'load', initialize);
//=============== ~animation funcitons =====================
var car = "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z";
var icon = {
path: car,
scale: .7,
strokeColor: 'white',
strokeWeight: .10,
fillOpacity: 1,
fillColor: '#404040',
offset: '5%',
// rotation: parseInt(heading[i]),
anchor: new google.maps.Point(10, 25) // orig 10,50 back of car, 10,0 front of car, 10,25 center of car
};
/*********************************************************************\
* *
* epolys.js by Mike Williams *
* updated to API v3 by Larry Ross *
* *
* A Google Maps API Extension *
* *
* Adds various Methods to google.maps.Polygon and google.maps.Polyline *
* *
* .Contains(latlng) returns true is the poly contains the specified *
* GLatLng *
* *
* .Area() returns the approximate area of a poly that is *
* not self-intersecting *
* *
* .Distance() returns the length of the poly path *
* *
* .Bounds() returns a GLatLngBounds that bounds the poly *
* *
* .GetPointAtDistance() returns a GLatLng at the specified distance *
* along the path. *
* The distance is specified in metres *
* Reurns null if the path is shorter than that *
* *
* .GetPointsAtDistance() returns an array of GLatLngs at the *
* specified interval along the path. *
* The distance is specified in metres *
* *
* .GetIndexAtDistance() returns the vertex number at the specified *
* distance along the path. *
* The distance is specified in metres *
* Returns null if the path is shorter than that *
* *
* .Bearing(v1?,v2?) returns the bearing between two vertices *
* if v1 is null, returns bearing from first to last *
* if v2 is null, returns bearing from v1 to next *
* *
* *
***********************************************************************
* *
* This Javascript is provided by Mike Williams *
* Blackpool Community Church Javascript Team *
* http://www.blackpoolchurch.org/ *
* http://econym.org.uk/gmap/ *
* *
* This work is licenced under a Creative Commons Licence *
* http://creativecommons.org/licenses/by/2.0/uk/ *
* *
***********************************************************************
* *
* Version 1.1 6-Jun-2007 *
* Version 1.2 1-Jul-2007 - fix: Bounds was omitting vertex zero *
* add: Bearing *
* Version 1.3 28-Nov-2008 add: GetPointsAtDistance() *
* Version 1.4 12-Jan-2009 fix: GetPointsAtDistance() *
* Version 3.0 11-Aug-2010 update to v3 *
* *
\*********************************************************************/
// === first support methods that don't (yet) exist in v3
google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
var EarthRadiusMeters = 6378137.0; // meters
var lat1 = this.lat();
var lon1 = this.lng();
var lat2 = newLatLng.lat();
var lon2 = newLatLng.lng();
var dLat = (lat2 - lat1) * Math.PI / 180;
var dLon = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = EarthRadiusMeters * c;
return d;
}
google.maps.LatLng.prototype.latRadians = function() {
return this.lat() * Math.PI / 180;
}
google.maps.LatLng.prototype.lngRadians = function() {
return this.lng() * Math.PI / 180;
}
// === A method which returns the length of a path in metres ===
google.maps.Polygon.prototype.Distance = function() {
var dist = 0;
for (var i = 1; i < this.getPath().getLength(); i++) {
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
return dist;
}
// === 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.Polygon.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 += this.getPath().getAt(i).distanceFrom(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);
}
// === A method which returns an array of GLatLngs of points a given interval along the path ===
google.maps.Polygon.prototype.GetPointsAtDistance = function(metres) {
var next = metres;
var points = [];
// some awkward special cases
if (metres <= 0) return points;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength()); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
while (dist > next) {
var p1 = this.getPath().getAt(i - 1);
var p2 = this.getPath().getAt(i);
var m = (next - olddist) / (dist - olddist);
points.push(new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m));
next += metres;
}
}
return points;
}
// === A method which returns the Vertex number at a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polygon.prototype.GetIndexAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
return i;
}
// === Copy all the above functions to GPolyline ===
google.maps.Polyline.prototype.Distance = google.maps.Polygon.prototype.Distance;
google.maps.Polyline.prototype.GetPointAtDistance = google.maps.Polygon.prototype.GetPointAtDistance;
google.maps.Polyline.prototype.GetPointsAtDistance = google.maps.Polygon.prototype.GetPointsAtDistance;
google.maps.Polyline.prototype.GetIndexAtDistance = google.maps.Polygon.prototype.GetIndexAtDistance;
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
font-family: Helvetica, Arial;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="tools">start:
<input type="text" name="start" id="start" value="union square, NY" />end:
<input type="text" name="end" id="end" value="times square, NY" />
<input type="submit" onclick="calcRoute();" />
</div>
<div id="map_canvas" style="width:100%;height:90%;"></div>

Easiest solution for this (FOR GOOGLE MAPS) :
var rotationAngle = google.maps.geometry.spherical.computeHeading(oldLatlng, currentlatlng);
$('img[src="path_to_marker_icon_image"]').css({
transform: "rotate(" + rotationAngle + "deg)"
});

You can use it easily do with the help of the 'GMSMapView' Delegates method.
var lastMapBearing: CLLocationDirection?
var lastUserBearing: CLLocationDirection?
func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
lastMapBearing = position.bearing
driverMarker?.rotation = (lastUserBearing ?? 0) - lastMapBearing!
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
lastUserBearing = newHeading.trueHeading
driverMarker?.rotation = lastUserBearing! - (lastMapBearing ?? 0)
}
Make sure you can assign the delegate itSelf.

Related

Google Maps MarkerCluster plus Spiderfier

A previous Q&A provided a great example of what I'm looking to do with a map, but I'm clearly missing something when I integrate portions into my own page, as I keep getting an error thrown and can't see where I'm wrong.
Previous Q&A :
Overlapping Pointers with MarkerClustererPlus and OverlappingMarkerSpiderfier
I'm working on a page for a directional route with waypoints and clustered markers at given distances along the route / polyline. It works great as is, but the icing would be Spiderfied clustered markers.
Here's my code so far :
var geocoder;
var map;
var marker;
var gmarkers = [];
var markerCluster;
var METERS_TO_MILES = 0.000621371192;
var walked = (Math.round(25000 * 1609.344));
var jMarkers = [
['Vehicle1', 16.1, '#1'],
['Vehicle1', 16.1, '#1'],
['Vehicle3', 25.2, '#45' ]
];
//ICON
var iconImage = {
url: 'https://maps.google.com/mapfiles/ms/micons/red.png',
size: new google.maps.Size(25, 34),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(16, 34)
};
//INFO WINDOW
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
//CREATE MARKER
function createMarker(latlng, label, team, html) {
var contentString = '<b>' + label + '</b><br>' + team + '<br>' + html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: iconImage,
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;
}
function initialize() {
var latlng = new google.maps.LatLng(51.469768, 0.261950);
var myOptions = {
zoom: 9,
maxZoom:16,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
google.maps.event.addListenerOnce(map, 'idle', function() {
var oms = new OverlappingMarkerSpiderfier(map, {
markersWontMove: true,
markersWontHide: true,
keepSpiderfied: true
});
});
// Add a marker clusterer to manage the markers.
markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
minClusterZoom = 14;
markerCluster.setMaxZoom(minClusterZoom);
var rendererOptions = {
map: map,
suppressMarkers: true,
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
//waypoints
var point1 = new google.maps.LatLng(51.679356, 0.124934);
var point2 = new google.maps.LatLng(51.714827, -0.392763);
var point3 = new google.maps.LatLng(51.494842, -0.494127);
var point4 = new google.maps.LatLng(51.526885, -0.498285);
var wps = [{
location: point1,
location: point2,
location: point3,
location: point4
}];
//START
var org = new google.maps.LatLng(51.469768, 0.261950);
//FINISH
var dest = new google.maps.LatLng(51.469768, 0.261950);
var request = {
origin: org,
destination: dest,
waypoints: wps,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//SHOW ROUTE
directionsDisplay.setDirections(response);
//COPY POLY FROM DIRECTION SERVICE
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 1
});
var bounds = new google.maps.LatLngBounds();
var lengthMeters = 0;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
if (lengthMeters <= walked) {
polyline.getPath().push(nextSegment[k]);
if (polyline.getPath().getLength() > 1) {
var lastPt = polyline.getPath().getLength() - 1;
lengthMeters += google.maps.geometry.spherical.computeDistanceBetween(polyline.getPath().getAt(lastPt - 1), polyline.getPath().getAt(lastPt));
}
}
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
var i;
for (i = 0; i < jMarkers.length; i++) {
walked = 0;
walked = (Math.round(jMarkers[i][1] * 1609.344));
markerCluster.addMarker(createMarker(polyline.GetPointAtDistance(walked), jMarkers[i][0], jMarkers[i][2], (Math.round(walked * METERS_TO_MILES * 10) / 10) + ' miles'));
}
oms.addMarker(createMarker(polyline.GetPointAtDistance(walked), jMarkers[i][0], jMarkers[i][2], (Math.round(walked * METERS_TO_MILES * 10) / 10) + ' miles'));
//GET THE TOTAL DISTANCE
var distance = 0;
//var METERS_TO_MILES = 0.000621371192;
for (i = 0; i < response.routes[0].legs.length; i++) {
//FOR EACH LEG GET THE DISTANCE AND ADD IT TO THE TOTAL
distance += parseFloat(response.routes[0].legs[i].distance.value);
}
alert(Math.round(distance * METERS_TO_MILES * 10) / 10 + ' miles');
} else if (status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED) {
alert('Max waypoints exceeded');
} else {
alert('failed to get directions');
}
});
};
window.onload = function() {
initialize();
};
/*********************************************************************\
* *
* epolys.js by Mike Williams *
* updated to API v3 by Larry Ross *
* *
* A Google Maps API Extension *
* *
* Adds various Methods to google.maps.Polygon and google.maps.Polyline *
* *
* .Contains(latlng) returns true is the poly contains the specified *
* GLatLng *
* *
* .Area() returns the approximate area of a poly that is *
* not self-intersecting *
* *
* .Distance() returns the length of the poly path *
* *
* .Bounds() returns a GLatLngBounds that bounds the poly *
* *
* .GetPointAtDistance() returns a GLatLng at the specified distance *
* along the path. *
* The distance is specified in metres *
* Reurns null if the path is shorter than that *
* *
* .GetPointsAtDistance() returns an array of GLatLngs at the *
* specified interval along the path. *
* The distance is specified in metres *
* *
* .GetIndexAtDistance() returns the vertex number at the specified *
* distance along the path. *
* The distance is specified in metres *
* Returns null if the path is shorter than that *
* *
* .Bearing(v1?,v2?) returns the bearing between two vertices *
* if v1 is null, returns bearing from first to last *
* if v2 is null, returns bearing from v1 to next *
* *
* *
***********************************************************************
* *
* This Javascript is provided by Mike Williams *
* Blackpool Community Church Javascript Team *
* http://www.blackpoolchurch.org/ *
* http://econym.org.uk/gmap/ *
* *
* This work is licenced under a Creative Commons Licence *
* http://creativecommons.org/licenses/by/2.0/uk/ *
* *
***********************************************************************
* *
* Version 1.1 6-Jun-2007 *
* Version 1.2 1-Jul-2007 - fix: Bounds was omitting vertex zero *
* add: Bearing *
* Version 1.3 28-Nov-2008 add: GetPointsAtDistance() *
* Version 1.4 12-Jan-2009 fix: GetPointsAtDistance() *
* Version 3.0 11-Aug-2010 update to v3 *
* *
\*********************************************************************/
// === first support methods that don't (yet) exist in v3
google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
var EarthRadiusMeters = 6378137.0; // meters
var lat1 = this.lat();
var lon1 = this.lng();
var lat2 = newLatLng.lat();
var lon2 = newLatLng.lng();
var dLat = (lat2 - lat1) * Math.PI / 180;
var dLon = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = EarthRadiusMeters * c;
return d;
}
google.maps.LatLng.prototype.latRadians = function() {
return this.lat() * Math.PI / 180;
}
google.maps.LatLng.prototype.lngRadians = function() {
return this.lng() * Math.PI / 180;
}
// === A method which returns the length of a path in metres ===
google.maps.Polygon.prototype.Distance = function() {
var dist = 0;
for (var i = 1; i < this.getPath().getLength(); i++) {
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
return dist;
}
// === 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.Polygon.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 += this.getPath().getAt(i).distanceFrom(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);
}
// === A method which returns an array of GLatLngs of points a given interval along the path ===
google.maps.Polygon.prototype.GetPointsAtDistance = function(metres) {
var next = metres;
var points = [];
// some awkward special cases
if (metres <= 0) return points;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength()); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
while (dist > next) {
var p1 = this.getPath().getAt(i - 1);
var p2 = this.getPath().getAt(i);
var m = (next - olddist) / (dist - olddist);
points.push(new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m));
next += metres;
}
}
return points;
}
// === A method which returns the Vertex number at a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polygon.prototype.GetIndexAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
return i;
}
// === Copy all the above functions to GPolyline ===
google.maps.Polyline.prototype.Distance = google.maps.Polygon.prototype.Distance;
google.maps.Polyline.prototype.GetPointAtDistance = google.maps.Polygon.prototype.GetPointAtDistance;
google.maps.Polyline.prototype.GetPointsAtDistance = google.maps.Polygon.prototype.GetPointsAtDistance;
google.maps.Polyline.prototype.GetIndexAtDistance = google.maps.Polygon.prototype.GetIndexAtDistance;
html,
body,
#map,
#container {
height: 100%;
width: 100%;
background: #000;
padding: 0px;
margin: 0px;
<div id="container">
<div id="map"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
<script src="https://jawj.github.io/OverlappingMarkerSpiderfier/bin/oms.min.js"></script>
I get a javascript error with your code snippet: Uncaught ReferenceError: oms is not defined, because that variable is local to the map idle event listener.
If I make it global, but leave it in the idle event listener, then I get a different error (because oms is not initialized when it is used).
Initializing it inline solves the issue, but I believe you want to add the same markers to the oms as you do to the MarkerClusterer (unless the functionality you are trying to implement is different than I am expecting)
for (i = 0; i < jMarkers.length; i++) {
walked = 0;
walked = (Math.round(jMarkers[i][1] * 1609.344));
var marker = createMarker(polyline.GetPointAtDistance(walked), jMarkers[i][0], jMarkers[i][2], (Math.round(walked * METERS_TO_MILES * 10) / 10) + ' miles');
markerCluster.addMarker(marker);
oms.addMarker(marker);
}
working code snippet:
var geocoder;
var map;
var oms;
var marker;
var gmarkers = [];
var markerCluster;
var METERS_TO_MILES = 0.000621371192;
var walked = (Math.round(25000 * 1609.344));
var jMarkers = [
['Vehicle1', 16.1, '#1'],
['Vehicle1', 16.1, '#1'],
['Vehicle3', 25.2, '#45']
];
//ICON
var iconImage = {
url: 'https://maps.google.com/mapfiles/ms/micons/red.png',
size: new google.maps.Size(25, 34),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(16, 34)
};
//INFO WINDOW
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
//CREATE MARKER
function createMarker(latlng, label, team, html) {
var contentString = '<b>' + label + '</b><br>' + team + '<br>' + html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: iconImage,
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;
}
function initialize() {
var latlng = new google.maps.LatLng(51.469768, 0.261950);
var myOptions = {
zoom: 9,
maxZoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
oms = new OverlappingMarkerSpiderfier(map, {
markersWontMove: true,
markersWontHide: true,
keepSpiderfied: true
});
// Add a marker clusterer to manage the markers.
markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
minClusterZoom = 14;
markerCluster.setMaxZoom(minClusterZoom);
var rendererOptions = {
map: map,
suppressMarkers: true,
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
//waypoints
var point1 = new google.maps.LatLng(51.679356, 0.124934);
var point2 = new google.maps.LatLng(51.714827, -0.392763);
var point3 = new google.maps.LatLng(51.494842, -0.494127);
var point4 = new google.maps.LatLng(51.526885, -0.498285);
var wps = [{
location: point1,
location: point2,
location: point3,
location: point4
}];
//START
var org = new google.maps.LatLng(51.469768, 0.261950);
//FINISH
var dest = new google.maps.LatLng(51.469768, 0.261950);
var request = {
origin: org,
destination: dest,
waypoints: wps,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//SHOW ROUTE
directionsDisplay.setDirections(response);
//COPY POLY FROM DIRECTION SERVICE
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 1
});
var bounds = new google.maps.LatLngBounds();
var lengthMeters = 0;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
if (lengthMeters <= walked) {
polyline.getPath().push(nextSegment[k]);
if (polyline.getPath().getLength() > 1) {
var lastPt = polyline.getPath().getLength() - 1;
lengthMeters += google.maps.geometry.spherical.computeDistanceBetween(polyline.getPath().getAt(lastPt - 1), polyline.getPath().getAt(lastPt));
}
}
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
var i;
for (i = 0; i < jMarkers.length; i++) {
walked = 0;
walked = (Math.round(jMarkers[i][1] * 1609.344));
var marker = createMarker(polyline.GetPointAtDistance(walked), jMarkers[i][0], jMarkers[i][2], (Math.round(walked * METERS_TO_MILES * 10) / 10) + ' miles');
markerCluster.addMarker(marker);
oms.addMarker(marker);
}
//GET THE TOTAL DISTANCE
var distance = 0;
//var METERS_TO_MILES = 0.000621371192;
for (i = 0; i < response.routes[0].legs.length; i++) {
//FOR EACH LEG GET THE DISTANCE AND ADD IT TO THE TOTAL
distance += parseFloat(response.routes[0].legs[i].distance.value);
}
console.log(Math.round(distance * METERS_TO_MILES * 10) / 10 + ' miles');
} else if (status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED) {
alert('Max waypoints exceeded');
} else {
alert('failed to get directions');
}
});
};
window.onload = function() {
initialize();
};
/*********************************************************************\
* *
* epolys.js by Mike Williams *
* updated to API v3 by Larry Ross *
* *
* A Google Maps API Extension *
* *
* Adds various Methods to google.maps.Polygon and google.maps.Polyline *
* *
* .Contains(latlng) returns true is the poly contains the specified *
* GLatLng *
* *
* .Area() returns the approximate area of a poly that is *
* not self-intersecting *
* *
* .Distance() returns the length of the poly path *
* *
* .Bounds() returns a GLatLngBounds that bounds the poly *
* *
* .GetPointAtDistance() returns a GLatLng at the specified distance *
* along the path. *
* The distance is specified in metres *
* Reurns null if the path is shorter than that *
* *
* .GetPointsAtDistance() returns an array of GLatLngs at the *
* specified interval along the path. *
* The distance is specified in metres *
* *
* .GetIndexAtDistance() returns the vertex number at the specified *
* distance along the path. *
* The distance is specified in metres *
* Returns null if the path is shorter than that *
* *
* .Bearing(v1?,v2?) returns the bearing between two vertices *
* if v1 is null, returns bearing from first to last *
* if v2 is null, returns bearing from v1 to next *
* *
* *
***********************************************************************
* *
* This Javascript is provided by Mike Williams *
* Blackpool Community Church Javascript Team *
* http://www.blackpoolchurch.org/ *
* http://econym.org.uk/gmap/ *
* *
* This work is licenced under a Creative Commons Licence *
* http://creativecommons.org/licenses/by/2.0/uk/ *
* *
***********************************************************************
* *
* Version 1.1 6-Jun-2007 *
* Version 1.2 1-Jul-2007 - fix: Bounds was omitting vertex zero *
* add: Bearing *
* Version 1.3 28-Nov-2008 add: GetPointsAtDistance() *
* Version 1.4 12-Jan-2009 fix: GetPointsAtDistance() *
* Version 3.0 11-Aug-2010 update to v3 *
* *
\*********************************************************************/
// === first support methods that don't (yet) exist in v3
google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
var EarthRadiusMeters = 6378137.0; // meters
var lat1 = this.lat();
var lon1 = this.lng();
var lat2 = newLatLng.lat();
var lon2 = newLatLng.lng();
var dLat = (lat2 - lat1) * Math.PI / 180;
var dLon = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = EarthRadiusMeters * c;
return d;
}
google.maps.LatLng.prototype.latRadians = function() {
return this.lat() * Math.PI / 180;
}
google.maps.LatLng.prototype.lngRadians = function() {
return this.lng() * Math.PI / 180;
}
// === A method which returns the length of a path in metres ===
google.maps.Polygon.prototype.Distance = function() {
var dist = 0;
for (var i = 1; i < this.getPath().getLength(); i++) {
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
return dist;
}
// === 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.Polygon.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 += this.getPath().getAt(i).distanceFrom(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);
}
// === A method which returns an array of GLatLngs of points a given interval along the path ===
google.maps.Polygon.prototype.GetPointsAtDistance = function(metres) {
var next = metres;
var points = [];
// some awkward special cases
if (metres <= 0) return points;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength()); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
while (dist > next) {
var p1 = this.getPath().getAt(i - 1);
var p2 = this.getPath().getAt(i);
var m = (next - olddist) / (dist - olddist);
points.push(new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m));
next += metres;
}
}
return points;
}
// === A method which returns the Vertex number at a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polygon.prototype.GetIndexAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
return i;
}
// === Copy all the above functions to GPolyline ===
google.maps.Polyline.prototype.Distance = google.maps.Polygon.prototype.Distance;
google.maps.Polyline.prototype.GetPointAtDistance = google.maps.Polygon.prototype.GetPointAtDistance;
google.maps.Polyline.prototype.GetPointsAtDistance = google.maps.Polygon.prototype.GetPointsAtDistance;
google.maps.Polyline.prototype.GetIndexAtDistance = google.maps.Polygon.prototype.GetIndexAtDistance;
html,
body,
#map,
#container {
height: 100%;
width: 100%;
background: #000;
padding: 0px;
margin: 0px;
<div id="container">
<div id="map"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
<script src="https://jawj.github.io/OverlappingMarkerSpiderfier/bin/oms.min.js"></script>

Google maps, route with multiple distance markers and clustering

I came across a previous question (Rocket Ronnie) and answer (Geocodezip) from a few years ago which I've successfully updated to place multiple makers at separate distances along a given route.
Google maps draw distance traveled polyline
The next step which I'm having issues with is adding clustering. I'm new to Google mapping, I've used the Google clustering examples and see how they work, but can't work out how to combine the two. Any guidance or pointers would be hugely appreciated.
Thanks in advance.
var geocoder;
var map;
var marker;
var gmarkers = [];
var METERS_TO_MILES = 0.000621371192;
var walked = (Math.round(550 * 1609.344));
var jMarkers = [
['Craig Smith', 16],
['Bob Smith', 36],
['John Jones', 76],
['John Jones', 75],
['Brett Jones', 123],
['John Peterson', 145],
['John Smith', 175]
];
//ICON
var iconImage = {
url: 'https://maps.google.com/mapfiles/ms/micons/red.png',
size: new google.maps.Size(25, 34), //MARKER SIZE (WxH)
origin: new google.maps.Point(0, 0), //MARKER ORIGIN
anchor: new google.maps.Point(16, 34) //MARKER ANCHOR
};
//INFO WINDOW
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
//CREATE MARKER
function createMarker(latlng, label, html) {
var contentString = '<b>' + label + '</b><br>' + html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: iconImage,
title: label,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
var markerCluster = new MarkerClusterer(map, marker,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
marker.myname = label;
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
return marker;
}
function initialize() {
var latlng = new google.maps.LatLng(51.555967, -0.279736);
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var rendererOptions = {
map: map,
suppressMarkers: true,
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
//waypoints
var point1 = new google.maps.LatLng(48.858469, 2.294353);
var wps = [
{location: point1}
];
//START
var org = new google.maps.LatLng(51.513872, -0.098329);
//FINISH
var dest = new google.maps.LatLng(45.465361, 9.191464);
var request = {
origin: org,
destination: dest,
waypoints: wps,
travelMode: google.maps.DirectionsTravelMode.WALKING,
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//SHOW ROUTE
directionsDisplay.setDirections(response);
//COPY POLY FROM DIRECTION SERVICE
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var lengthMeters = 0;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
if (lengthMeters <= walked) {
polyline.getPath().push(nextSegment[k]);
if (polyline.getPath().getLength() > 1) {
var lastPt = polyline.getPath().getLength() - 1;
lengthMeters += google.maps.geometry.spherical.computeDistanceBetween(polyline.getPath().getAt(lastPt - 1), polyline.getPath().getAt(lastPt));
}
}
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
var i;
for (i = 0; i < jMarkers.length; i++) {
walked = 0;
walked = (Math.round(jMarkers[i][1] * 1609.344));
createMarker(polyline.GetPointAtDistance(walked), jMarkers[i][0], (Math.round(walked * METERS_TO_MILES * 10) / 10) + ' miles');
}
//ADD MARKER TO NEW POLYLINE AT 'X' DISTANCE
// createMarker(polyline.GetPointAtDistance(walked), "You are here", (Math.round(walked * METERS_TO_MILES * 10) / 10) + ' miles');
//GET THE TOTAL DISTANCE
var distance = 0;
//var METERS_TO_MILES = 0.000621371192;
for (i = 0; i < response.routes[0].legs.length; i++) {
//FOR EACH LEG GET THE DISTANCE AND ADD IT TO THE TOTAL
distance += parseFloat(response.routes[0].legs[i].distance.value);
}
} else if (status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED) {
alert('Max waypoints exceeded');
} else {
alert('failed to get directions');
}
});
};
window.onload = function() {
initialize();
};
/*********************************************************************\
* *
* epolys.js by Mike Williams *
* updated to API v3 by Larry Ross *
* *
* A Google Maps API Extension *
* *
* Adds various Methods to google.maps.Polygon and google.maps.Polyline *
* *
* .Contains(latlng) returns true is the poly contains the specified *
* GLatLng *
* *
* .Area() returns the approximate area of a poly that is *
* not self-intersecting *
* *
* .Distance() returns the length of the poly path *
* *
* .Bounds() returns a GLatLngBounds that bounds the poly *
* *
* .GetPointAtDistance() returns a GLatLng at the specified distance *
* along the path. *
* The distance is specified in metres *
* Reurns null if the path is shorter than that *
* *
* .GetPointsAtDistance() returns an array of GLatLngs at the *
* specified interval along the path. *
* The distance is specified in metres *
* *
* .GetIndexAtDistance() returns the vertex number at the specified *
* distance along the path. *
* The distance is specified in metres *
* Returns null if the path is shorter than that *
* *
* .Bearing(v1?,v2?) returns the bearing between two vertices *
* if v1 is null, returns bearing from first to last *
* if v2 is null, returns bearing from v1 to next *
* *
* *
***********************************************************************
* *
* This Javascript is provided by Mike Williams *
* Blackpool Community Church Javascript Team *
* http://www.blackpoolchurch.org/ *
* http://econym.org.uk/gmap/ *
* *
* This work is licenced under a Creative Commons Licence *
* http://creativecommons.org/licenses/by/2.0/uk/ *
* *
***********************************************************************
* *
* Version 1.1 6-Jun-2007 *
* Version 1.2 1-Jul-2007 - fix: Bounds was omitting vertex zero *
* add: Bearing *
* Version 1.3 28-Nov-2008 add: GetPointsAtDistance() *
* Version 1.4 12-Jan-2009 fix: GetPointsAtDistance() *
* Version 3.0 11-Aug-2010 update to v3 *
* *
\*********************************************************************/
// === first support methods that don't (yet) exist in v3
google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
var EarthRadiusMeters = 6378137.0; // meters
var lat1 = this.lat();
var lon1 = this.lng();
var lat2 = newLatLng.lat();
var lon2 = newLatLng.lng();
var dLat = (lat2 - lat1) * Math.PI / 180;
var dLon = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = EarthRadiusMeters * c;
return d;
}
google.maps.LatLng.prototype.latRadians = function() {
return this.lat() * Math.PI / 180;
}
google.maps.LatLng.prototype.lngRadians = function() {
return this.lng() * Math.PI / 180;
}
// === A method which returns the length of a path in metres ===
google.maps.Polygon.prototype.Distance = function() {
var dist = 0;
for (var i = 1; i < this.getPath().getLength(); i++) {
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
return dist;
}
// === 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.Polygon.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 += this.getPath().getAt(i).distanceFrom(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);
}
// === A method which returns an array of GLatLngs of points a given interval along the path ===
google.maps.Polygon.prototype.GetPointsAtDistance = function(metres) {
var next = metres;
var points = [];
// some awkward special cases
if (metres <= 0) return points;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength()); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
while (dist > next) {
var p1 = this.getPath().getAt(i - 1);
var p2 = this.getPath().getAt(i);
var m = (next - olddist) / (dist - olddist);
points.push(new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m));
next += metres;
}
}
return points;
}
// === A method which returns the Vertex number at a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polygon.prototype.GetIndexAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
return i;
}
// === Copy all the above functions to GPolyline ===
google.maps.Polyline.prototype.Distance = google.maps.Polygon.prototype.Distance;
google.maps.Polyline.prototype.GetPointAtDistance = google.maps.Polygon.prototype.GetPointAtDistance;
google.maps.Polyline.prototype.GetPointsAtDistance = google.maps.Polygon.prototype.GetPointsAtDistance;
google.maps.Polyline.prototype.GetIndexAtDistance = google.maps.Polygon.prototype.GetIndexAtDistance;
html,
body,
#map,
#container {
height: 100%;
width: 100%;
background: #000;
padding: 0px;
margin: 0px;
}
<div id="container">
<div id="map"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
</script>
Related question: I am trying to add marker clusters to my google maps script
Proof of concept fiddle fixing your syntax errors, creating the MarkerClusterer at the beginning and adding the markers to it when they are returned from the createMarker function.
function initialize() {
var latlng = new google.maps.LatLng(51.555967, -0.279736);
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
// Add a marker clusterer to manage the markers.
markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
// ...
Then in your loop that creates the markers:
for (i = 0; i < jMarkers.length; i++) {
walked = 0;
walked = (Math.round(jMarkers[i][1] * 1609.344));
markerCluster.addMarker(createMarker(polyline.GetPointAtDistance(walked), jMarkers[i][0], (Math.round(walked * METERS_TO_MILES * 10) / 10) + ' miles'));
}
code snippet:
var geocoder;
var map;
var marker;
var gmarkers = [];
var markerCluster;
var METERS_TO_MILES = 0.000621371192;
var walked = (Math.round(550 * 1609.344));
var jMarkers = [
['Craig Smith', 16],
['Bob Smith', 36],
['John Jones', 76],
['John Jones', 75],
['Brett Jones', 123],
['John Peterson', 145],
['John Smith', 175]
];
//ICON
var iconImage = {
url: 'https://maps.google.com/mapfiles/ms/micons/red.png',
size: new google.maps.Size(25, 34), //MARKER SIZE (WxH)
origin: new google.maps.Point(0, 0), //MARKER ORIGIN
anchor: new google.maps.Point(16, 34) //MARKER ANCHOR
};
//INFO WINDOW
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
//CREATE MARKER
function createMarker(latlng, label, html) {
var contentString = '<b>' + label + '</b><br>' + html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: iconImage,
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;
}
function initialize() {
var latlng = new google.maps.LatLng(51.555967, -0.279736);
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
// Add a marker clusterer to manage the markers.
markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
var rendererOptions = {
map: map,
suppressMarkers: true,
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
//waypoints
var point1 = new google.maps.LatLng(48.858469, 2.294353);
var wps = [{
location: point1
}];
//START
var org = new google.maps.LatLng(51.513872, -0.098329);
//FINISH
var dest = new google.maps.LatLng(45.465361, 9.191464);
var request = {
origin: org,
destination: dest,
waypoints: wps,
travelMode: google.maps.DirectionsTravelMode.WALKING,
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//SHOW ROUTE
directionsDisplay.setDirections(response);
//COPY POLY FROM DIRECTION SERVICE
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var lengthMeters = 0;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
if (lengthMeters <= walked) {
polyline.getPath().push(nextSegment[k]);
if (polyline.getPath().getLength() > 1) {
var lastPt = polyline.getPath().getLength() - 1;
lengthMeters += google.maps.geometry.spherical.computeDistanceBetween(polyline.getPath().getAt(lastPt - 1), polyline.getPath().getAt(lastPt));
}
}
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
var i;
for (i = 0; i < jMarkers.length; i++) {
walked = 0;
walked = (Math.round(jMarkers[i][1] * 1609.344));
markerCluster.addMarker(createMarker(polyline.GetPointAtDistance(walked), jMarkers[i][0], (Math.round(walked * METERS_TO_MILES * 10) / 10) + ' miles'));
}
//ADD MARKER TO NEW POLYLINE AT 'X' DISTANCE
// createMarker(polyline.GetPointAtDistance(walked), "You are here", (Math.round(walked * METERS_TO_MILES * 10) / 10) + ' miles');
//GET THE TOTAL DISTANCE
var distance = 0;
//var METERS_TO_MILES = 0.000621371192;
for (i = 0; i < response.routes[0].legs.length; i++) {
//FOR EACH LEG GET THE DISTANCE AND ADD IT TO THE TOTAL
distance += parseFloat(response.routes[0].legs[i].distance.value);
}
} else if (status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED) {
alert('Max waypoints exceeded');
} else {
alert('failed to get directions');
}
});
};
window.onload = function() {
initialize();
};
/*********************************************************************\
* *
* epolys.js by Mike Williams *
* updated to API v3 by Larry Ross *
* *
* A Google Maps API Extension *
* *
* Adds various Methods to google.maps.Polygon and google.maps.Polyline *
* *
* .Contains(latlng) returns true is the poly contains the specified *
* GLatLng *
* *
* .Area() returns the approximate area of a poly that is *
* not self-intersecting *
* *
* .Distance() returns the length of the poly path *
* *
* .Bounds() returns a GLatLngBounds that bounds the poly *
* *
* .GetPointAtDistance() returns a GLatLng at the specified distance *
* along the path. *
* The distance is specified in metres *
* Reurns null if the path is shorter than that *
* *
* .GetPointsAtDistance() returns an array of GLatLngs at the *
* specified interval along the path. *
* The distance is specified in metres *
* *
* .GetIndexAtDistance() returns the vertex number at the specified *
* distance along the path. *
* The distance is specified in metres *
* Returns null if the path is shorter than that *
* *
* .Bearing(v1?,v2?) returns the bearing between two vertices *
* if v1 is null, returns bearing from first to last *
* if v2 is null, returns bearing from v1 to next *
* *
* *
***********************************************************************
* *
* This Javascript is provided by Mike Williams *
* Blackpool Community Church Javascript Team *
* http://www.blackpoolchurch.org/ *
* http://econym.org.uk/gmap/ *
* *
* This work is licenced under a Creative Commons Licence *
* http://creativecommons.org/licenses/by/2.0/uk/ *
* *
***********************************************************************
* *
* Version 1.1 6-Jun-2007 *
* Version 1.2 1-Jul-2007 - fix: Bounds was omitting vertex zero *
* add: Bearing *
* Version 1.3 28-Nov-2008 add: GetPointsAtDistance() *
* Version 1.4 12-Jan-2009 fix: GetPointsAtDistance() *
* Version 3.0 11-Aug-2010 update to v3 *
* *
\*********************************************************************/
// === first support methods that don't (yet) exist in v3
google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
var EarthRadiusMeters = 6378137.0; // meters
var lat1 = this.lat();
var lon1 = this.lng();
var lat2 = newLatLng.lat();
var lon2 = newLatLng.lng();
var dLat = (lat2 - lat1) * Math.PI / 180;
var dLon = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = EarthRadiusMeters * c;
return d;
}
google.maps.LatLng.prototype.latRadians = function() {
return this.lat() * Math.PI / 180;
}
google.maps.LatLng.prototype.lngRadians = function() {
return this.lng() * Math.PI / 180;
}
// === A method which returns the length of a path in metres ===
google.maps.Polygon.prototype.Distance = function() {
var dist = 0;
for (var i = 1; i < this.getPath().getLength(); i++) {
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
return dist;
}
// === 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.Polygon.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 += this.getPath().getAt(i).distanceFrom(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);
}
// === A method which returns an array of GLatLngs of points a given interval along the path ===
google.maps.Polygon.prototype.GetPointsAtDistance = function(metres) {
var next = metres;
var points = [];
// some awkward special cases
if (metres <= 0) return points;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength()); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
while (dist > next) {
var p1 = this.getPath().getAt(i - 1);
var p2 = this.getPath().getAt(i);
var m = (next - olddist) / (dist - olddist);
points.push(new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m));
next += metres;
}
}
return points;
}
// === A method which returns the Vertex number at a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polygon.prototype.GetIndexAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
return i;
}
// === Copy all the above functions to GPolyline ===
google.maps.Polyline.prototype.Distance = google.maps.Polygon.prototype.Distance;
google.maps.Polyline.prototype.GetPointAtDistance = google.maps.Polygon.prototype.GetPointAtDistance;
google.maps.Polyline.prototype.GetPointsAtDistance = google.maps.Polygon.prototype.GetPointsAtDistance;
google.maps.Polyline.prototype.GetIndexAtDistance = google.maps.Polygon.prototype.GetIndexAtDistance;
html,
body,
#map,
#container {
height: 100%;
width: 100%;
background: #000;
padding: 0px;
margin: 0px;
}
<div id="container">
<div id="map"></div>
</div>
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Google maps draw distance traveled polyline

I would like to draw a 'distance traveled' polyline over a preset route using V3 of the google maps API.
The polyline would need to run through multiple waypoints/legs.
I am currently using the DirectionsService to draw the complete route.
I am also using epolys.js to get the marker position for the distance traveled.
I am copying the complete route into a new polyline, but I would only like to copy the route up to the marker position.
Demo link: http://codepen.io/1983ron/pen/wKMVQr
And here's where I'm currently at with the JS
var geocoder;
var map;
var marker;
var gmarkers = [];
var METERS_TO_MILES = 0.000621371192;
var walked = (Math.round(670 * 1609.344));
//ICON
var iconImage = new google.maps.MarkerImage(
'http://www.ronnieatkinson.co.uk/clients/wc2015/maps/01/mapIcons/marker_red.png', //MARKER URL
new google.maps.Size(20, 34), //MARKER SIZE (WxH)
new google.maps.Point(0,0), //MARKER ORIGIN
new google.maps.Point(9, 34) //MARKER ANCHOR
);
//SHADOW
var iconShadow = new google.maps.MarkerImage(
'http://www.google.com/mapfiles/shadow50.png', //SHADOW URL
new google.maps.Size(37, 34), //SHADOW SIZE (WxH)
new google.maps.Point(0,0), //SHADOW ORIGIN
new google.maps.Point(9, 34) //SHADOW ANCHOR
);
//INFO WINDOW
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
//CREATE MARKER
function createMarker(latlng, label, html) {
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: iconShadow,
icon: iconImage,
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;
}
function initialize() {
var latlng = new google.maps.LatLng(51.555967, -0.279736);
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var rendererOptions = {
map: map,
suppressMarkers: true,
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
//Edinburgh to Eden Project
var point1 = new google.maps.LatLng(58.981386, -2.973751); //Orkney Rugby Football Club
var point2 = new google.maps.LatLng(55.881517, -4.342057); //Scotstoun Stadium
var point3 = new google.maps.LatLng(54.998080, -7.319812); //Guildhall St
var point4 = new google.maps.LatLng(54.563716, -5.942729); //Belfast Harlequins RFC
var point5 = new google.maps.LatLng(53.271057, -9.054253); //Hotel Spanish Arch
var point6 = new google.maps.LatLng(52.674222, -8.642515); //Thomond Park
var point7 = new google.maps.LatLng(53.291755, -3.713769); //Colwyn Leisure Centre
var point8 = new google.maps.LatLng(51.748180, -3.618567); //Glynneath Rugby Football Club
var wps = [
{ location: point1 },
{ location: point2 },
{ location: point3 },
{ location: point4 },
{ location: point5 },
{ location: point6 },
{ location: point7 },
{ location: point8 }
];
//START
var org = new google.maps.LatLng (55.945315, -3.205309); //EDINBURGH
//FINISH
var dest = new google.maps.LatLng (50.360130, -4.744717); //EDEN PROJECT
var request = {
origin: org,
destination: dest,
waypoints: wps,
travelMode: google.maps.DirectionsTravelMode.WALKING,
//unitSystem: google.maps.UnitSystem.IMPERIAL
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//SHOW ROUTE
directionsDisplay.setDirections(response);
//COPY POLY FROM DIRECTION SERVICE
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
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);
//alert(walked);
//ADD MARKER TO NEW POLYLINE AT 'X' DISTANCE
createMarker(polyline.GetPointAtDistance(walked), "You are here", (Math.round( walked * METERS_TO_MILES * 10 ) / 10)+' miles');
//GET THE TOTAL DISTANCE
var distance= 0;
//var METERS_TO_MILES = 0.000621371192;
for(i = 0; i < response.routes[0].legs.length; i++){
//FOR EACH LEG GET THE DISTANCE AND ADD IT TO THE TOTAL
distance += parseFloat(response.routes[0].legs[i].distance.value);
}
//alert((Math.round( distance * METERS_TO_MILES * 10 ) / 10)+' miles');
//alert(distance); //METERS
} else if(status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED){
alert ('Max waypoints exceeded');
} else {
alert ('failed to get directions');
}
});
};window.onload = function() { initialize(); };
Any help would be appreciated.
Calculate the length of the line as you create it. Once it becomes greater than or equal to the distance "walked", stop adding points to it.
var lengthMeters = 0;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
if (lengthMeters <= walked) {
// if polyline is less than distance "walked", keep adding to it
polyline.getPath().push(nextSegment[k]);
if (polyline.getPath().getLength() > 1) {
var lastPt = polyline.getPath().getLength() - 1;
lengthMeters += google.maps.geometry.spherical.computeDistanceBetween(polyline.getPath().getAt(lastPt - 1), polyline.getPath().getAt(lastPt));
}
}
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
proof of concept fiddle
code snippet:
var geocoder;
var map;
var marker;
var gmarkers = [];
var METERS_TO_MILES = 0.000621371192;
var walked = (Math.round(670 * 1609.344));
//ICON
var iconImage = {
url: 'http://www.ronnieatkinson.co.uk/clients/wc2015/maps/01/mapIcons/marker_red.png', //MARKER URL
size: new google.maps.Size(20, 34), //MARKER SIZE (WxH)
origin: new google.maps.Point(0, 0), //MARKER ORIGIN
anchor: new google.maps.Point(9, 34) //MARKER ANCHOR
};
//INFO WINDOW
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
//CREATE MARKER
function createMarker(latlng, label, html) {
var contentString = '<b>' + label + '</b><br>' + html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: iconImage,
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;
}
function initialize() {
var latlng = new google.maps.LatLng(51.555967, -0.279736);
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var rendererOptions = {
map: map,
suppressMarkers: true,
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
//Edinburgh to Eden Project
var point1 = new google.maps.LatLng(58.981386, -2.973751); //Orkney Rugby Football Club
var point2 = new google.maps.LatLng(55.881517, -4.342057); //Scotstoun Stadium
var point3 = new google.maps.LatLng(54.998080, -7.319812); //Guildhall St
var point4 = new google.maps.LatLng(54.563716, -5.942729); //Belfast Harlequins RFC
var point5 = new google.maps.LatLng(53.271057, -9.054253); //Hotel Spanish Arch
var point6 = new google.maps.LatLng(52.674222, -8.642515); //Thomond Park
var point7 = new google.maps.LatLng(53.291755, -3.713769); //Colwyn Leisure Centre
var point8 = new google.maps.LatLng(51.748180, -3.618567); //Glynneath Rugby Football Club
var wps = [{
location: point1
}, {
location: point2
}, {
location: point3
}, {
location: point4
}, {
location: point5
}, {
location: point6
}, {
location: point7
}, {
location: point8
}];
//START
var org = new google.maps.LatLng(55.945315, -3.205309); //EDINBURGH
//FINISH
var dest = new google.maps.LatLng(50.360130, -4.744717); //EDEN PROJECT
var request = {
origin: org,
destination: dest,
waypoints: wps,
travelMode: google.maps.DirectionsTravelMode.WALKING,
//unitSystem: google.maps.UnitSystem.IMPERIAL
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//SHOW ROUTE
directionsDisplay.setDirections(response);
//COPY POLY FROM DIRECTION SERVICE
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var lengthMeters = 0;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
if (lengthMeters <= walked) {
polyline.getPath().push(nextSegment[k]);
if (polyline.getPath().getLength() > 1) {
var lastPt = polyline.getPath().getLength() - 1;
lengthMeters += google.maps.geometry.spherical.computeDistanceBetween(polyline.getPath().getAt(lastPt - 1), polyline.getPath().getAt(lastPt));
}
}
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
//alert(walked);
//ADD MARKER TO NEW POLYLINE AT 'X' DISTANCE
createMarker(polyline.GetPointAtDistance(walked), "You are here", (Math.round(walked * METERS_TO_MILES * 10) / 10) + ' miles');
//GET THE TOTAL DISTANCE
var distance = 0;
//var METERS_TO_MILES = 0.000621371192;
for (i = 0; i < response.routes[0].legs.length; i++) {
//FOR EACH LEG GET THE DISTANCE AND ADD IT TO THE TOTAL
distance += parseFloat(response.routes[0].legs[i].distance.value);
}
//alert((Math.round( distance * METERS_TO_MILES * 10 ) / 10)+' miles');
//alert(distance); //METERS
} else if (status == google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED) {
alert('Max waypoints exceeded');
} else {
alert('failed to get directions');
}
});
};
window.onload = function() {
initialize();
};
/*********************************************************************\
* *
* epolys.js by Mike Williams *
* updated to API v3 by Larry Ross *
* *
* A Google Maps API Extension *
* *
* Adds various Methods to google.maps.Polygon and google.maps.Polyline *
* *
* .Contains(latlng) returns true is the poly contains the specified *
* GLatLng *
* *
* .Area() returns the approximate area of a poly that is *
* not self-intersecting *
* *
* .Distance() returns the length of the poly path *
* *
* .Bounds() returns a GLatLngBounds that bounds the poly *
* *
* .GetPointAtDistance() returns a GLatLng at the specified distance *
* along the path. *
* The distance is specified in metres *
* Reurns null if the path is shorter than that *
* *
* .GetPointsAtDistance() returns an array of GLatLngs at the *
* specified interval along the path. *
* The distance is specified in metres *
* *
* .GetIndexAtDistance() returns the vertex number at the specified *
* distance along the path. *
* The distance is specified in metres *
* Returns null if the path is shorter than that *
* *
* .Bearing(v1?,v2?) returns the bearing between two vertices *
* if v1 is null, returns bearing from first to last *
* if v2 is null, returns bearing from v1 to next *
* *
* *
***********************************************************************
* *
* This Javascript is provided by Mike Williams *
* Blackpool Community Church Javascript Team *
* http://www.blackpoolchurch.org/ *
* http://econym.org.uk/gmap/ *
* *
* This work is licenced under a Creative Commons Licence *
* http://creativecommons.org/licenses/by/2.0/uk/ *
* *
***********************************************************************
* *
* Version 1.1 6-Jun-2007 *
* Version 1.2 1-Jul-2007 - fix: Bounds was omitting vertex zero *
* add: Bearing *
* Version 1.3 28-Nov-2008 add: GetPointsAtDistance() *
* Version 1.4 12-Jan-2009 fix: GetPointsAtDistance() *
* Version 3.0 11-Aug-2010 update to v3 *
* *
\*********************************************************************/
// === first support methods that don't (yet) exist in v3
google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
var EarthRadiusMeters = 6378137.0; // meters
var lat1 = this.lat();
var lon1 = this.lng();
var lat2 = newLatLng.lat();
var lon2 = newLatLng.lng();
var dLat = (lat2 - lat1) * Math.PI / 180;
var dLon = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = EarthRadiusMeters * c;
return d;
}
google.maps.LatLng.prototype.latRadians = function() {
return this.lat() * Math.PI / 180;
}
google.maps.LatLng.prototype.lngRadians = function() {
return this.lng() * Math.PI / 180;
}
// === A method which returns the length of a path in metres ===
google.maps.Polygon.prototype.Distance = function() {
var dist = 0;
for (var i = 1; i < this.getPath().getLength(); i++) {
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
return dist;
}
// === 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.Polygon.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 += this.getPath().getAt(i).distanceFrom(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);
}
// === A method which returns an array of GLatLngs of points a given interval along the path ===
google.maps.Polygon.prototype.GetPointsAtDistance = function(metres) {
var next = metres;
var points = [];
// some awkward special cases
if (metres <= 0) return points;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength()); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
while (dist > next) {
var p1 = this.getPath().getAt(i - 1);
var p2 = this.getPath().getAt(i);
var m = (next - olddist) / (dist - olddist);
points.push(new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m));
next += metres;
}
}
return points;
}
// === A method which returns the Vertex number at a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polygon.prototype.GetIndexAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
return i;
}
// === Copy all the above functions to GPolyline ===
google.maps.Polyline.prototype.Distance = google.maps.Polygon.prototype.Distance;
google.maps.Polyline.prototype.GetPointAtDistance = google.maps.Polygon.prototype.GetPointAtDistance;
google.maps.Polyline.prototype.GetPointsAtDistance = google.maps.Polygon.prototype.GetPointsAtDistance;
google.maps.Polyline.prototype.GetIndexAtDistance = google.maps.Polygon.prototype.GetIndexAtDistance;
html,
body,
#map,
#container {
height: 100%;
width: 100%;
background: #000;
padding: 0px;
margin: 0px;
}
<div id="container">
<div id="map"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
</script>

Can I get Google Maps v3 to draw polylines independently?

I'm trying to animate the path of a tracked vehicle on a Google Map (v3 API). I have 4 polylines: one being a grey background line to indicate the entire route, and 3 more to indicate the previous hours worth of tracking data (red for the past 10 minutes, orange for 10-30 minutes and yellow for 30-60 minutes).
Even though I've set the zIndex correctly for the polylines, as I create the new animated lines and destroy the old ones the grey background line keeps overlapping the other lines (I don't touch this polyline during animation).
It also seriously reduces the performance of the animation, if I disable the grey line the performance is just fine.
I believe what's happening is that Google Maps is using one canvas element to draw all the polylines that intersect that rectangle, so it has to redraw all of my polylines in that rectangle, not just the ones I'm animating. Is there any way to get Google Maps to put them on separate layers so it only redraws the ones I want to redraw?
Update: I've created a sample that performs pretty well, but does demonstrate the background line overlapping the other lines.
HTML:
<button>Animate</button> <div id="slider"/>
<div id="map" style="height: 600px; margin-top: 20px;"/>
Javascript:
google.maps.LatLng.prototype.destinationPoint = function(brng, dist) {
dist = dist / 6371;
brng = brng.toRad();
var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
Math.cos(lat1),
Math.cos(dist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
var range_lines = {
red: null,
orange: null,
yellow: null
};
var range_colors = {
red: '#ff0000',
orange: '#FFA500',
yellow: '#FFFF00'
};
function onSlide(e, ui) {
var end_minute = ui.value;
var start_minute = Math.max(0, end_minute - 60);
var line_points = [];
var last_range = null;
var last_point = null;
for (var minute = start_minute; minute < end_minute; minute++) {
var diff = Math.abs(end_minute - minute);
var range = '';
if (diff <= 10) {
range = 'red';
} else if (diff <= 30) {
range = 'orange';
} else {
range = 'yellow';
}
if (range != last_range) {
renderLine(line_points, last_range);
line_points = [];
last_range = range;
}
if (points_by_minute.hasOwnProperty(minute)) {
for (var i = 0; i < points_by_minute[minute].length; i++) {
line_points.push(points[points_by_minute[minute][i]]);
last_point = points[points_by_minute[minute][i]];
}
}
}
marker.setPosition(last_point);
renderLine(line_points, last_range);
}
function renderLine(line_points, range) {
var line = new google.maps.Polyline({
path: line_points,
strokeColor: range_colors[range],
strokeWeight: 3,
map: map,
zIndex: getZIndex(range)
});
if (range_lines[range] != null) {
range_lines[range].setMap(null);
}
range_lines[range] = line;
}
function getZIndex(range) {
switch (range) {
case 'yellow':
return 10;
case 'orange':
return 20;
case 'red':
return 30;
}
}
var points = [];
var points_by_minute = {};
var map;
var marker;
var interval;
$(document).ready(function() {
var start_point = new google.maps.LatLng(51.3767, -0.0960);
var point = new google.maps.LatLng(51.3767, -0.0960);
var minute = 0;
var bearing = 0;
var bounds = new google.maps.LatLngBounds()
for (var i = 0; i < 5000; i++) {
if (Math.random() > 0.5) {
if (Math.random() > 0.5) {
bearing += Math.round(Math.random() * 10);
} else {
bearing -= Math.round(Math.random() * 10);
}
}
if (i != 0 && i % 12 == 0) {
minute++;
}
if (!points_by_minute.hasOwnProperty(minute)) {
points_by_minute[minute] = [];
}
points_by_minute[minute].push(points.length);
point = point.destinationPoint(bearing, 0.01);
points.push(point);
bounds.extend(point);
}
for (var i = 0; i < 5000; i++) {
if (i != 0 && i % 12 == 0) {
minute++;
}
if (!points_by_minute.hasOwnProperty(minute)) {
points_by_minute[minute] = [];
}
points_by_minute[minute].push(points.length);
var latJitter = Math.random() / 10000;
if (Math.random() > 0.5) {
latJitter = -latJitter;
}
var lngJitter = Math.random() / 10000;
if (Math.random() > 0.5) {
lngJitter = -lngJitter;
}
point = new google.maps.LatLng(
points[4999 - i].lat() + latJitter,
points[4999 - i].lng() + lngJitter
);
points.push(point);
}
map = new google.maps.Map($('#map')[0], {
center: start_point,
zoom: 8,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
map.fitBounds(bounds);
$('button').button().click(function() {
if (interval) clearInterval(interval);
var value = $('#slider').slider("option", "value");
if (value == $('#slider').slider("option", "max")) {
clearInterval(interval);
}
$('#slider').slider("option", "value", $('#slider').slider("option", "min"));
interval = setInterval(animate, 10);
});
$('#slider').slider({
min: 0,
max: minute++,
step: 1,
value: 0,
change: onSlide
});
new google.maps.Polyline({
path: points,
strokeColor: '#cccccc',
strokeWeight: 1.5,
map: map,
zIndex: 1
});
marker = new google.maps.Marker({
position: start_point,
map: map
});
});
function animate() {
var value = $('#slider').slider("option", "value");
value++;
$('#slider').slider("option", "value", value);
if (value == $('#slider').slider("option", "max")) {
clearInterval(interval);
}
}

Draw circle's arc on google maps

The idea is to draw an arc centered on a specific point, using angles.
Note: Not the chord, nor the sector, nor the area between the chord and the arc.
Memento: http://en.wikipedia.org/wiki/Arc_(geometry)
A full circle parameters:
- center at coordinates LatC,LngC
- radius of 1 609 meters
- start angle of 0 degrees
- end angle of 360 degrees
example http://jsfiddle.net/GGvQH/3/
new google.maps.Circle({
center: new google.maps.LatLng(18.4894, 73.910158),
radius: 1609,
...
});
An arc of 180° (PI/2 radiant) oriented to north would be like:
- center at coordinates LatC,LngC
- radius of 1 609 meters
- start angle of 270 degrees (9 o'clock)
- end angle of 90 degrees (3 o'clock)
First of all, I do not want to plot a polyline for each arc, using tons of points to get a smooth effect: need to recompute for each scale and may cost resources... or is it?
There is an idea with polygons intersection
Google Maps API v3 - circle sector
...do anyone have seen a working jsfiddle?
Note: http://jsfiddle.net/Morlock0821/4dRB2/1/ is very close to the arc, but I do not want a closed surface.
Another idea with bearing... but I am reluctant to redefine the earth's radius to get the tiny arc I want.
https://developers.google.com/maps/documentation/javascript/examples/geometry-headings
(in this case, I want only the purple line, not the red one).
Any help would be greatly appreciated.
This is the code I use in this example:
function drawArc(center, initialBearing, finalBearing, radius) {
var d2r = Math.PI / 180; // degrees to radians
var r2d = 180 / Math.PI; // radians to degrees
var points = 32;
// find the raidus in lat/lon
var rlat = (radius / EarthRadiusMeters) * r2d;
var rlng = rlat / Math.cos(center.lat() * d2r);
var extp = new Array();
if (initialBearing > finalBearing) finalBearing += 360;
var deltaBearing = finalBearing - initialBearing;
deltaBearing = deltaBearing/points;
for (var i=0; (i < points+1); i++)
{
extp.push(center.DestinationPoint(initialBearing + i*deltaBearing, radius));
bounds.extend(extp[extp.length-1]);
}
return extp;
}
Used like this, where startPoint is the start of the arc, endPoint is the end of the arc and centerPoint is the center, but you can specify center, angles and radius.
var arcPts = drawArc(centerPoint, centerPoint.Bearing(startPoint), centerPoint.Bearing(endPoint), centerPoint.distanceFrom(startPoint));
var piePoly = new google.maps.Polygon({
paths: [arcPts],
strokeColor: "#00FF00",
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map
});
Ancillary functions, may no longer be necessary if you include the geometry library
var EarthRadiusMeters = 6378137.0; // meters
/* Based the on the Latitude/longitude spherical geodesy formulae & scripts
at http://www.movable-type.co.uk/scripts/latlong.html
(c) Chris Veness 2002-2010
*/
google.maps.LatLng.prototype.DestinationPoint = function (brng, dist) {
var R = EarthRadiusMeters; // earth's mean radius in meters
var brng = brng.toRad();
var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
var lat2 = Math.asin( Math.sin(lat1)*Math.cos(dist/R) +
Math.cos(lat1)*Math.sin(dist/R)*Math.cos(brng) );
var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(dist/R)*Math.cos(lat1),
Math.cos(dist/R)-Math.sin(lat1)*Math.sin(lat2));
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
// === A function which returns the bearing between two LatLng in radians ===
// === If v1 is null, it returns the bearing between the first and last vertex ===
// === If v1 is present but v2 is null, returns the bearing from v1 to the next vertex ===
// === If either vertex is out of range, returns void ===
google.maps.LatLng.prototype.Bearing = function(otherLatLng) {
var from = this;
var to = otherLatLng;
if (from.equals(to)) {
return 0;
}
var lat1 = from.latRadians();
var lon1 = from.lngRadians();
var lat2 = to.latRadians();
var lon2 = to.lngRadians();
var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
if ( angle < 0.0 ) angle += Math.PI * 2.0;
if ( angle > Math.PI ) angle -= Math.PI * 2.0;
return parseFloat(angle.toDeg());
}
/**
* Extend the Number object to convert degrees to radians
*
* #return {Number} Bearing in radians
* #ignore
*/
Number.prototype.toRad = function () {
return this * Math.PI / 180;
};
/**
* Extend the Number object to convert radians to degrees
*
* #return {Number} Bearing in degrees
* #ignore
*/
Number.prototype.toDeg = function () {
return this * 180 / Math.PI;
};
/**
* Normalize a heading in degrees to between 0 and +360
*
* #return {Number} Return
* #ignore
*/
Number.prototype.toBrng = function () {
return (this.toDeg() + 360) % 360;
};
code snippet (using geometry library):
var EarthRadiusMeters = 6378137.0; // meters
/* Based the on the Latitude/longitude spherical geodesy formulae & scripts
at http://www.movable-type.co.uk/scripts/latlong.html
(c) Chris Veness 2002-2010
*/
google.maps.LatLng.prototype.DestinationPoint = function(brng, dist) {
var R = EarthRadiusMeters; // earth's mean radius in meters
var brng = brng.toRad();
var lat1 = this.lat().toRad(),
lon1 = this.lng().toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist / R) +
Math.cos(lat1) * Math.sin(dist / R) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist / R) * Math.cos(lat1),
Math.cos(dist / R) - Math.sin(lat1) * Math.sin(lat2));
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
/**
* Extend the Number object to convert degrees to radians
*
* #return {Number} Bearing in radians
* #ignore
*/
Number.prototype.toRad = function() {
return this * Math.PI / 180;
};
/**
* Extend the Number object to convert radians to degrees
*
* #return {Number} Bearing in degrees
* #ignore
*/
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
};
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
bounds.extend(latlng);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
function drawArc(center, initialBearing, finalBearing, radius) {
var d2r = Math.PI / 180; // degrees to radians
var r2d = 180 / Math.PI; // radians to degrees
var points = 32;
// find the raidus in lat/lon
var rlat = (radius / EarthRadiusMeters) * r2d;
var rlng = rlat / Math.cos(center.lat() * d2r);
var extp = new Array();
if (initialBearing > finalBearing) finalBearing += 360;
var deltaBearing = finalBearing - initialBearing;
deltaBearing = deltaBearing / points;
for (var i = 0;
(i < points + 1); i++) {
extp.push(center.DestinationPoint(initialBearing + i * deltaBearing, radius));
bounds.extend(extp[extp.length - 1]);
}
return extp;
}
function drawCircle(point, radius) {
var d2r = Math.PI / 180; // degrees to radians
var r2d = 180 / Math.PI; // radians to degrees
var EarthRadiusMeters = 6378137.0; // meters
var earthsradius = 3963; // 3963 is the radius of the earth in miles
var points = 32;
// find the raidus in lat/lon
var rlat = (radius / EarthRadiusMeters) * r2d;
var rlng = rlat / Math.cos(point.lat() * d2r);
var extp = new Array();
for (var i = 0; i < points + 1; i++) // one extra here makes sure we connect the
{
var theta = Math.PI * (i / (points / 2));
ey = point.lng() + (rlng * Math.cos(theta)); // center a + radius x * cos(theta)
ex = point.lat() + (rlat * Math.sin(theta)); // center b + radius y * sin(theta)
extp.push(new google.maps.LatLng(ex, ey));
bounds.extend(extp[extp.length - 1]);
}
// alert(extp.length);
return extp;
}
var map = null;
var bounds = null;
function initialize() {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(-33.9, 151.2),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
bounds = new google.maps.LatLngBounds();
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var startPoint = new google.maps.LatLng(48.610335003092956, -1.6123447775299600);
var endPoint = new google.maps.LatLng(48.596190206866830, -1.5551704322317228);
var centerPoint = new google.maps.LatLng(48.565630000000006, -1.6050300000000002);
createMarker(startPoint, "start: " + startPoint.toUrlValue(6) + "<br>distance to center: " + (google.maps.geometry.spherical.computeDistanceBetween(centerPoint, startPoint) / 1000).toFixed(3) + " km<br>Bearing: " + google.maps.geometry.spherical.computeHeading(centerPoint, startPoint) + "<br><a href='javascript:map.setCenter(new google.maps.LatLng(" + startPoint.toUrlValue(6) + "));map.setZoom(20);'>zoom in</a> - <a href='javascript:map.fitBounds(bounds);'>zoom out</a>");
createMarker(endPoint, "end: " + endPoint.toUrlValue(6) + "<br>distance to center: " + (google.maps.geometry.spherical.computeDistanceBetween(centerPoint, endPoint) / 1000).toFixed(3) + " km<br>Bearing: " + google.maps.geometry.spherical.computeHeading(centerPoint, endPoint) + "<br><a href='javascript:map.setCenter(new google.maps.LatLng(" + endPoint.toUrlValue(6) + "));map.setZoom(20);'>zoom in</a> - <a href='javascript:map.fitBounds(bounds);'>zoom out</a>");
createMarker(centerPoint, "center: " + centerPoint.toUrlValue(6));
var arcPts = drawArc(centerPoint, google.maps.geometry.spherical.computeHeading(centerPoint, startPoint), google.maps.geometry.spherical.computeHeading(centerPoint, endPoint), google.maps.geometry.spherical.computeDistanceBetween(centerPoint, startPoint));
// add the start and end lines
arcPts.push(centerPoint);
bounds.extend(centerPoint);
arcPts.push(startPoint);
var piePoly = new google.maps.Polygon({
paths: [arcPts],
strokeColor: "#00FF00",
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map
});
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=geometry"></script>
<div id="map_canvas"></div>

Categories

Resources