Labeling GoogleMaps Lat/Lng intersection - javascript

I create a map with latitude and longitude lines drawn every 1/4 min. The resulting boxes are called Quarter Minutes. I need to label each Quarter Minute box. The label should be the lat/lon of the SW corner inside the box. Since I draw all the latitude lines within the viewing area first, and then all the longitude lines, I cannot figure out how to find the intersect point. It would seem, that I would draw one(1) latitude line, and then one(1) longitude line and then label the intersect. I figure I can just use an info box at each point.
I do not know how to do this in JavaScript. Maybe it is not necessary to trap the intersection at the point of creation but that is the only way I would think it would happen.
The syntax for a QtrMin is
3040A8415A = intersect at 30 40' by 84 15'
3040A8415B = intersect at 30 40' by 84 15' 15"
3040A8415C = intersect at 30 40' by 84 15' 30"
3040A8415D = intersect at 30 40' by 84 15' 45"
or DDMM and A-> D to designate each quarter of minute.
Longitude and latitude are treated the same.
What I have is:
<html>
<head>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry&sensor=false"></script>
<title>Find your Qtr minute locator</title>
</head>
<body style="height:100%;margin:0">
<!-- Declare the div, make it take up the full document body -->
<div id="map-canvas" style="width: 100%; height: 100%;"></div>
<script type="text/javascript">
var map;
var llOffset = 0.0666666666666667;
var drawGridBox = false;
var gridOverBox = new google.maps.Polyline({
path: [],
geodesic: true,
strokeColor: '',
strokeOpacity: 0,
strokeWeight: 0
});
var gridline;
var polylinesquare;
var latPolylines = [];
var lngPolylines = [];
var smLngPolylines = [];
var lngLabels = [];
var lngMapLabel;
var bounds = new google.maps.LatLngBounds();
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(34.00, -84.00),
zoom: 10,
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true
});
DrawGridOn();
google.maps.event.addListener(map, 'idle', function () {
createGridLines(map.getBounds());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function DrawGridOn() {
drawGridBox = true;
}
function DrawGridOff() {
drawGridBox = false;
}
function createGridLines(bounds) {
for (var i = 0; i < latPolylines.length; i++) {
latPolylines[i].setMap(null);
}
latPolylines = [];
for (var i = 0; i < lngPolylines.length; i++) {
lngPolylines[i].setMap(null);
}
lngPolylines = [];
if (map.getZoom() < 10) return;
var north = bounds.getNorthEast().lat();
var east = bounds.getNorthEast().lng();
var south = bounds.getSouthWest().lat();
var west = bounds.getSouthWest().lng();
// define the size of the grid
var topLat = Math.ceil(north / llOffset) * llOffset;
var rightLong = Math.ceil(east / llOffset) * llOffset;
var bottomLat = Math.floor(south / llOffset) * llOffset;
var leftLong = Math.floor(west / llOffset) * llOffset;
for (var latitude = bottomLat; latitude <= topLat; latitude += llOffset) latPolylines.push(new google.maps.Polyline({
path: [
new google.maps.LatLng(latitude, leftLong), new google.maps.LatLng(latitude, rightLong)],
map: map,
geodesic: true,
strokeColor: '#0000FF',
strokeOpacity: 0.5,
strokeWeight: 1
}));
for (var longitude = leftLong; longitude <= rightLong; longitude += llOffset) lngPolylines.push(new google.maps.Polyline({
path: [
new google.maps.LatLng(topLat, longitude), new google.maps.LatLng(bottomLat, longitude)],
map: map,
geodesic: true,
strokeColor: '#0000FF',
strokeOpacity: 0.5,
strokeWeight: 1
}));
}
</script>
</body>
</html>

Maybe it is not necessary to trap the intersection at the point of creation but that is the only way I would think it would happen
You draw straight lines with either equal latitudes or longitudes, so you may assume that the intersection of 2 lines:
latLine a: ay1,ax1 ay1,ax2
lngLine b: by1,bx1 by2,bx1
...is ay1,bx1
When the lines have been created iterate over them and create the labels based on the latitudes/longitudes:
//put the next 4 lines to the top of createGridLines
for(var i=0;i<lngLabels.length;++i){
lngLabels[i].setMap(null);
}
lngLabels=[];
//put this at the end of createGridLines
for(var x=0;x<latPolylines.length;++x){
for(var y=0;y<lngPolylines.length-1;++y){
var latLng=new google.maps.LatLng(latPolylines[x].getPath().getAt(0).lat(),
lngPolylines[y].getPath().getAt(0).lng());
lngLabels.push(new google.maps.Marker({
map:map,
position:latLng,
icon:{ url:'https://chart.googleapis.com/chart?'
+'chst=d_bubble_text_small&chld=bb|'
+ latLng.toUrlValue()
+'|FFFFFF|000000',
anchor:new google.maps.Point(0,42)
}
}));
}
}

Related

How to get Google map draw polygon area? [duplicate]

This question already has answers here:
Easiest way to calculate area of drawn polygon with google map
(1 answer)
Calculating area of a polygon drawn on google map
(2 answers)
Closed last month.
I don't have much experience in JavaScript. I am trying to get Area of polygon may be i am doing something wrong. I am using Google API. Every thing working good but unable to get draw polygon area. Below I have also uploaded one image on which I have draw polygon. Can anyone tell me how to find it's area.
var map;
var infoWindow;
var listOfPolygons = [];
var pdata = [
[43.7711057, -79.3696734, "Amritsar"],
[43.7442141, -79.407609, "oyeji"],
[43.7452141, -79.407609, "oyeji"],
];
function initMap() {
var locations = pdata;
var markers = [];
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 43.717899, lng: -79.6582408 },
zoom: 5,
streetViewControl: false,
mapTypeControl: false
});
//Drawing tool
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON,
],
}
})
drawingManager.setMap(map);
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
markers.push(
new google.maps.Marker({
position: {
lat: locations[i][0],
lng: locations[i][1]
},
title:"Amritsar"
})
);
bounds.extend(markers[markers.length - 1].getPosition());
}
map.fitBounds(bounds);
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
var poly = event.overlay.getPath();
//console.log(poly);
if (event.type == 'polygon') {
// hide polygon from DrawingManager
event.overlay.setMap(null);
//console.log(event.overlay.getPath().getArray());
listOfPolygons.push(new google.maps.Polygon({
paths: event.overlay.getPath().getArray(),
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
}));
//console.log(markers.length);
for (var i = 0; i < markers.length; i++) {
if (google.maps.geometry.poly.containsLocation(markers[i].getPosition(), listOfPolygons[listOfPolygons.length - 1])) {
// show current marker
markers[i].setMap(map);
console.log(markers[i].getPosition());
}
}
listOfPolygons[listOfPolygons.length - 1].setMap(map);
listOfPolygons[listOfPolygons.length - 1].addListener('click', showArrays);
}
});
infoWindow = new google.maps.InfoWindow({
content : "Amritsar"
});
/** #this {google.maps.Polygon} */
function showArrays(event) {
// Since this polygon has only one path, we can call getPath() to return the
// MVCArray of LatLngs.
var vertices = this.getPath();
var contentString = '<b>polygon</b><br>' +
'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
'<br>';
// Iterate over the vertices.
for (var i = 0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
xy.lng();
}
// Replace the info window's content and position.
//console.log(contentString);
infoWindow.setContent(contentString);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
}

Google Maps Api draw my polygon (rectangle) as parallelogram

I can't manage with drawing rectangle between two cities. I've searched everywhere on the Internet and can't find out why my polygon is drawn on Google Maps as parallelogram even so on 2d plane (not earth plane) this rectangle is drawn properly.
What I noticed is that the curvature sides of parallelogram depends on where cities are placed on map. If two cities are placed vis-a-vis then my function draw rectangle successfully. But If they are placed diagonally then my function draw parallelogram. The result should be rotated rectangle with height as distance between two cities and width as kilometers that user chooses.
Here is my function that should draw rectangle between two cities. As args we need to give position of first city ($x1 is lat, $y1 is lng), position of second city and as third arg a radius in kilometers ($l1) from center point of rectangle.
function getPolygon($x1,$y1,$x2,$y2,$l1){
var $l1 = $l1*0.010526; //approx kilometers
var $distanceV = [($x2 - $x1), ($y2 - $y1)];
var $vlen = Math.sqrt(Math.pow($distanceV[0], 2) +
Math.pow($distanceV[1],2));
if($vlen == 0)
return [[0,0],[0,0],[0,0],[0,0]];
var $l2 = $vlen;
var $normalized = [($distanceV[0] / $vlen), ($distanceV[1] / $vlen)];
var $rotated = [(-1 * $normalized[1]), ($normalized[0])];
var $p1 = [($x1 - $rotated[0] * $l1 / 2), ($y1 - $rotated[1] * $l1 / 2)];
var $p2 = [($p1[0] + $rotated[0] * $l1), ($p1[1] + $rotated[1] * $l1)];
var $p3 = [($p1[0] + $normalized[0] * $l2), ($p1[1] + $normalized[1] * $l2)];
var $p4 = [($p3[0] + $rotated[0] * $l1), ($p3[1] + $rotated[1] * $l1)];
var $points = [
{lat: $p1[0], lng: $p1[1]},
{lat: $p3[0], lng: $p3[1]},
{lat: $p4[0], lng: $p4[1]},
{lat: $p2[0], lng: $p2[1]},
{lat: $p1[0], lng: $p1[1]}
];
return $points;
}
Then I draw it on Google Maps like this:
new google.maps.Polygon({
paths: getPolygon(first_city_lat, first_city_lng, second_city_lat, second_city_lng, 30),
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.05
});
Here is an example should be rectangle between Birmingham and Oxford: JSFiddle
Additionally I'm sure that kilometers converter is not exact and it again depends how cities are placed.
The earth is curved. To get a polygon that appears rectangular on the curved sphere, you need to use calculations that take the projection of the map into account.
The Google Maps Javascript API v3 has a spherical geometry library that can be used to compute the desired points.
function getPolygon($x1,$y1,$x2,$y2,$l1){
var points = [];
var city1 = new google.maps.LatLng($x1, $y1);
var city2 = new google.maps.LatLng($x2, $y2);
var heading = google.maps.geometry.spherical.computeHeading(city1, city2);
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1/2*1000, heading+90));
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1/2*1000, heading-90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1/2*1000, heading-90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1/2*1000, heading+90));
points.push(points[0]);
return points;
}
proof of concept fiddle
code snippet:
var map;
google.maps.event.addDomListener(window, "load", function() {
var map = new google.maps.Map(document.getElementById("map_div"), {
center: new google.maps.LatLng(52.489471, -1.898575),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var trace = new google.maps.Polygon({
paths: getPolygon(52.489471, -1.898575, 51.752022, -1.257677, 30),
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.05,
map: map
});
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < trace.getPath().getLength(); i++) {
bounds.extend(trace.getPath().getAt(i));
}
map.fitBounds(bounds);
function getPolygon($x1, $y1, $x2, $y2, $l1) {
var points = [];
var city1 = new google.maps.LatLng($x1, $y1);
var city2 = new google.maps.LatLng($x2, $y2);
var heading = google.maps.geometry.spherical.computeHeading(city1, city2);
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1 / 2 * 1000, heading + 90));
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1 / 2 * 1000, heading - 90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1 / 2 * 1000, heading - 90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1 / 2 * 1000, heading + 90));
points.push(points[0]);
return points;
}
});
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
#map_div {
height: 95%;
}
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map_div"></div>

Drawing a path as an object moves on a map

I have this marker that moves along a google map http://jsfiddle.net/t43kaeyr/ but i need it to draw its path on the map as it moves.
This is the javascript that creates the map
var map,marker;
var startPos = [42.42679066670903, -83.29210638999939];
var speed = 150; // km/h
var delay = 100;
// If you set the delay below 1000ms and you go to another tab,
// the setTimeout function will wait to be the active tab again
// before running the code.
// See documentation :
// https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Inactive_tabs
function animateMarker(marker, coords, km_h)
{
var target = 0;
var km_h = km_h || 50;
coords.push([startPos[0], startPos[1]]);
function goToPoint()
{
var lat = marker.position.lat();
var lng = marker.position.lng();
var step = (km_h * 1000 * delay) / 3600000; // in meters
var dest = new google.maps.LatLng(
coords[target][0], coords[target][1]);
var distance =
google.maps.geometry.spherical.computeDistanceBetween(
dest, marker.position); // in meters
var numStep = distance / step;
var i = 0;
var deltaLat = (coords[target][0] - lat) / numStep;
var deltaLng = (coords[target][1] - lng) / numStep;
function moveMarker()
{
lat += deltaLat;
lng += deltaLng;
i += step;
if (i < distance)
{
marker.setPosition(new google.maps.LatLng(lat, lng));
setTimeout(moveMarker, delay);
}
else
{ marker.setPosition(dest);
target++;
if (target == coords.length){ target = 0; }
setTimeout(goToPoint, delay);
}
}
moveMarker();
}
goToPoint();
}
function initialize()
{
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(42.425175091823974, -83.2943058013916),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
position: new google.maps.LatLng(startPos[0], startPos[1]),
icon: 'assets/images/c.png',
map: map
});
google.maps.event.addListenerOnce(map, 'idle', function()
{
animateMarker(marker, [
// The coordinates of each point you want the marker to go to.
// You don't need to specify the starting position again.
[42.42666395645802, -83.29694509506226],
[42.42300508749226, -83.29679489135742],
[42.42304468678425, -83.29434871673584],
[42.424882066428424, -83.2944130897522],
[42.42495334300206, -83.29203128814697]
], speed);
});
}
initialize();
I tried drawing the path and the path is drawn correctly but the object does not move any more. This is the code
var map,marker;
var startPos = [42.42679066670903, -83.29210638999939];
var speed = 150; // km/h
var delay = 100;
// If you set the delay below 1000ms and you go to another tab,
// the setTimeout function will wait to be the active tab again
// before running the code.
// See documentation :
// https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Inactive_tabs
function animateMarker(marker, coords, km_h)
{
var target = 0;
var km_h = km_h || 50;
coords.push([startPos[0], startPos[1]]);
function goToPoint()
{
var lat = marker.position.lat();
var lng = marker.position.lng();
var step = (km_h * 1000 * delay) / 3600000; // in meters
var dest = new google.maps.LatLng(
coords[target][0], coords[target][1]);
var distance =
google.maps.geometry.spherical.computeDistanceBetween(
dest, marker.position); // in meters
var numStep = distance / step;
var i = 0;
var deltaLat = (coords[target][0] - lat) / numStep;
var deltaLng = (coords[target][1] - lng) / numStep;
function moveMarker()
{
lat += deltaLat;
lng += deltaLng;
i += step;
if (i < distance)
{
marker.setPosition(new google.maps.LatLng(lat, lng));
setTimeout(moveMarker, delay);
}
else
{ marker.setPosition(dest);
target++;
if (target == coords.length){ target = 0; }
setTimeout(goToPoint, delay);
}
}
moveMarker();
}
goToPoint();
}
function initialize()
{
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(42.425175091823974, -83.2943058013916),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
position: new google.maps.LatLng(startPos[0], startPos[1]),
icon: 'assets/images/c.png',
map: map
});
var flightPlanCoordinates = [
{lat: 42.42666395645802, lng: -83.29694509506226},
{lat: 42.42300508749226, lng: -83.29679489135742},
{lat: 42.42304468678425, lng: -83.29434871673584},
{lat: 42.424882066428424, lng: -83.2944130897522},
{lat: 42.42495334300206, lng: -83.29203128814697}
];
google.maps.event.addListenerOnce(map, 'idle', function()
{
animateMarker(marker, [
// The coordinates of each point you want the marker to go to.
// You don't need to specify the starting position again.
flightPlanCoordinates
], speed);
});
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
initialize();
How can i make the marker to draw its path as it moves on the map?.
Maybe you want create a Polyline with a Line with multiple points, which represents each position of the marker:
provide a global variable:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var polylineCoords = [];
var path = new google.maps.Polyline({
path: polylineCoords,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path.setMap(map);
//To add a Point on the polyline call
function addCoord(lat, lng) {
var point = new google.maps.LatLng(lat, lng);
var coords = path.getPath();
coords.push(point);
}
JSFiddle

Draw a smaller Polygon inside a Polygon using Google Maps

I am trying to render shapes on Google Maps (using V3 of the API), which contain the same shape, just smaller inside. Basically a box within a box or a polygon within a polygon.
For the rectangle I have the following code, which works:
var drawEdgesRectangle = function (shape) {
// shape is the original, parent rectangle
var NE, SW, childNE, childSW, padding, diagonal, inner;
// set padding constant to 1 (i.e. 1m distance all around)
padding = 1;
// get diagonal distance from corner
diagonal = Math.sqrt(2) * padding;
// get NE of parent
NE = shape.bounds.getNorthEast();
// get SW of parent
SW = shape.bounds.getSouthWest();
// get child NE, SW
childNE = google.maps.geometry.spherical.computeOffset(NE, diagonal, 225);
childSW = google.maps.geometry.spherical.computeOffset(SW, diagonal, 45);
// render inner shape
inner = new google.maps.Rectangle({
strokeColor: 'white',
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: 'black',
fillOpacity: 0.35,
map: map,
bounds: new google.maps.LatLngBounds(
childSW,
childNE
)
});
}
Of course, doing this for a polygon is a different kettle of fish. I know I can use getPaths() to get the attributes of each line, but working out how to place the inner lines, and indeed, work out where 'inside' is is proving to be conceptually quite difficult for me.
I would like to know if what I want to achieve is possible given the Google API.
One option if you polygons are "simple" (the center is "inside" the polygon and there are no concave sides), would be to do something similar to what you did with the rectangle (which is a four sided polygon that meets those criteria):
Using the geometry library:
To include it:
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry"></script>
Code (assumes global "poly" and others):
var drawEdgesPoly = function() {
// shape is the original, parent polygon
var shape = poly;
// set padding constant to 1 (i.e. 1m distance all around)
padding = 50;
var vertices = shape.getPath();
var polybounds = new google.maps.LatLngBounds();
for (var i = 0; i < vertices.getLength(); i++) {
polybounds.extend(vertices.getAt(i));
}
var center = polybounds.getCenter();
if (centerMarker && centerMarker.setMap) {
centerMarker.setMap(null);
}
centerMarker = new google.maps.Marker({
position: center,
map: map,
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(4, 4)
}
});
if (polylines && (polylines.length > 0)) {
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
}
polylines = [];
var newPath = [];
for (var i = 0; i < vertices.getLength(); i++) {
polylines.push(new google.maps.Polyline({
path: [center, vertices.getAt(i)],
map: map,
strokeWidth: 2,
strokeColor: 'red'
}));
newPath[i] = google.maps.geometry.spherical.computeOffset(vertices.getAt(i),
padding,
google.maps.geometry.spherical.computeHeading(vertices.getAt(i), center));
}
if (inner && inner.setMap)
inner.setMap(null);
// render inner shape
inner = new google.maps.Polygon({
strokeColor: 'white',
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: 'black',
fillOpacity: 0.35,
map: map,
editable: false,
path: newPath
});
};
proof of concept fiddle
Play with the polygon in the code snippet or the jsfiddle to see the constraints.
var map;
var infoWindow;
var poly;
var inner;
var polylines = [];
var centerMarker;
var paths = [
[
new google.maps.LatLng(38.872886, -77.054720),
new google.maps.LatLng(38.872602, -77.058046),
new google.maps.LatLng(38.870080, -77.058604),
new google.maps.LatLng(38.868894, -77.055664),
new google.maps.LatLng(38.870598, -77.053346)
]
];
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(38.8714, -77.0556),
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
poly = new google.maps.Polygon({
paths: paths,
strokeWeight: 3,
fillColor: '#55FF55',
fillOpacity: 0.5,
editable: true
});
poly.setMap(map);
drawEdgesPoly();
google.maps.event.addListener(poly.getPath(), 'insert_at', drawEdgesPoly);
google.maps.event.addListener(poly.getPath(), 'remove_at', drawEdgesPoly);
google.maps.event.addListener(poly.getPath(), 'set_at', drawEdgesPoly);
// Define an info window on the map.
infoWindow = new google.maps.InfoWindow();
}
google.maps.event.addDomListener(window, 'load', initialize);
var drawEdgesPoly = function() {
// shape is the original, parent polygon
var shape = poly;
// set padding constant to 1 (i.e. 1m distance all around)
padding = 50;
var vertices = shape.getPath();
var polybounds = new google.maps.LatLngBounds();
for (var i = 0; i < vertices.getLength(); i++) {
polybounds.extend(vertices.getAt(i));
}
var center = polybounds.getCenter();
if (centerMarker && centerMarker.setMap) {
centerMarker.setMap(null);
}
centerMarker = new google.maps.Marker({
position: center,
map: map,
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(4, 4)
}
});
if (polylines && (polylines.length > 0)) {
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
}
polylines = [];
var newPath = [];
for (var i = 0; i < vertices.getLength(); i++) {
polylines.push(new google.maps.Polyline({
path: [center, vertices.getAt(i)],
map: map,
strokeWidth: 2,
strokeColor: 'red'
}));
newPath[i] = google.maps.geometry.spherical.computeOffset(vertices.getAt(i),
padding,
google.maps.geometry.spherical.computeHeading(vertices.getAt(i), center));
}
if (inner && inner.setMap)
inner.setMap(null);
// render inner shape
inner = new google.maps.Polygon({
strokeColor: 'white',
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: 'black',
fillOpacity: 0.35,
map: map,
editable: false,
path: newPath
});
};
html,
body,
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry"></script>
<div id="map-canvas" style="height:100%; width:100%;"></div>

draw multiple polylines on map with different colors

I have a JSON array with multiple routes of latitudes and longitudes. It looks like the following:
My requirement is to draw each journey on the map using different colors, but my script draws all the journeys in one color:
The code used is:
<script>
function initialize() {
var jsonValues = '<?php echo $json; ?>';
var oJsonObj = JSON.parse(jsonValues);
console.log(oJsonObj);
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(6.932088333333334, 79.84256166666667),
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var numJournies = Object.size(oJsonObj);
var journey = [];
$.each(oJsonObj, function(ind,val){
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
color= "rgb("+r+" ,"+g+","+ b+")";
var journey = [];
$.each(val, function(i,v){
journey.push(new google.maps.LatLng(v.latitude, v.longitude));
});
polyline = new google.maps.Polyline({
path: journey,
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 3
});
polyline.setMap(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Any help will be greatly appreciated.
Regards,
Take one Array With Different colors.
var Colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFFFF", "#000000", "#FFFF00", "#00FFFF", "#FF00FF"];
Now, instead of drawing one polyline, draw a separate polyline for each coordinate.
for (var i = 0; i < DrivePath.length-1; i++) {
var PathStyle = new google.maps.Polyline({
path: [DrivePath[i], DrivePath[i+1]],
strokeColor: Colors[i],
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
}

Categories

Resources