Create Multiple stacked polylines on Google map with different colours - google-maps

Looking to create multiple routes from Location a to location B using Polylines on Google map.
I am having issue in giving colours to two polylines stacked over each other.
Basic use is to show progress in route traversed from A to B with the one already covered in orange and the left route in grey colour.
I am able to give colour to only one Polyline. The other polyline superimposed is not seen even when opacity of the top polyline is reduced.
See JSfiddle- https://jsfiddle.net/8yx3vLo6/3/
I am able to give colour to only one Polyline. The other polyline superimposed/stacked is not seen even when opacity of the top polyline is reduced.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: 'terrain'
});
var flightPlanCoordinates = [
{lat: 37.772, lng: -122.220},
{lat: 21.291, lng: -160.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: 'red',
strokeOpacity: 1.0,
strokeWeight: 1
});
flightPath.setMap(map);
var map1 = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: 'terrain'
});
var flightPlanCoordinates1 = [
{lat: 17.772, lng: -35.220},
{lat: 21.291, lng: -160.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var flightPath1 = new google.maps.Polyline({
path: flightPlanCoordinates1,
geodesic: true,
strokeColor: '#000',
strokeOpacity: 1,
strokeWeight: 1
});
flightPath1.setMap(map1);
}

You currently have 2 maps (map and map1). One polyline is on map the other on map1. First thing you need to do is put each polyline on the same map.
To make it so you can see both, put one on top of the other, with the one on top having a smaller stroke.
var flightPlanCoordinates = [
{lat: 37.772, lng: -122.220},
{lat: 21.291, lng: -160.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: 'yellow',
strokeOpacity: 1.0,
strokeWeight: 6 // first polyline added is on bottom, make stroke bigger
});
flightPath.setMap(map);
var flightPlanCoordinates1 = [
{lat: 37.772, lng: -122.220},
{lat: 21.291, lng: -160.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var flightPath1 = new google.maps.Polyline({
path: flightPlanCoordinates1,
geodesic: true,
strokeColor: 'blue',
strokeOpacity: 1.0,
strokeWeight: 2 // second polyline added is on top, make stroke smaller
});
flightPath1.setMap(map);
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 0,
lng: -180
},
mapTypeId: 'terrain'
});
var flightPlanCoordinates = [
{lat: 37.772, lng: -122.220},
{lat: 21.291, lng: -160.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: 'yellow',
strokeOpacity: 1.0,
strokeWeight: 6 // first polyline added is on bottom, make stroke bigger
});
flightPath.setMap(map);
var flightPlanCoordinates1 = [
{lat: 37.772, lng: -122.220},
{lat: 21.291, lng: -160.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var flightPath1 = new google.maps.Polyline({
path: flightPlanCoordinates1,
geodesic: true,
strokeColor: 'blue',
strokeOpacity: 1.0,
strokeWeight: 2 // second polyline added is on top, make stroke smaller
});
flightPath1.setMap(map);
var bounds = new google.maps.LatLngBounds();
bounds.extend(flightPlanCoordinates1[0]);
bounds.extend(flightPlanCoordinates1[3]);
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Related

How to correctly add a square grid inside a polygon using turfjs?

So i'm currently playing around with turfjs. And i'm trying to add a squaregrid inside a polygon.
So here's the code
var triangleCoords = [
{ lat: 25.774, lng: -80.19 },
{ lat: 18.466, lng: -66.118 },
{ lat: 32.321, lng: -64.757 },
{ lat: 25.774, lng: -80.19 }
];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
const geoJSON = {
type: 'Polygon',
coordinates: []
};
// convert to bermudaTriangle path to geojson
for (let point of bermudaTriangle.getPath().getArray()) {
geoJSON.coordinates.push([point.lat(), point.lng()]);
}
const feature = turf.feature(geoJSON);
const bbox = turf.bbox(feature);
// ERROR: this one's showing Infinity values
console.table(bbox);
const grid = turf.squareGrid(bbox, 50, {
units: "miles",
mask: feature
});
map.data.addGeoJson(grid);
and looking at the console, it shows Infinity values for bbox as commented on the code.
I've added a link for the code
https://codepen.io/chan-dev/pen/yrdRoM
geoJSON is not a valid GeoJSON object for Polygon in the provided example, that's the reason why turf.bbox returns invalid result. GeoJSON for polygon could be constructed via turf.polygon like this:
var triangleCoords = [
{ lat: 25.774, lng: -80.19 },
{ lat: 18.466, lng: -66.118 },
{ lat: 32.321, lng: -64.757 },
{ lat: 25.774, lng: -80.19 }
];
var data = triangleCoords.map(coord => {
return [coord.lng, coord.lat];
});
var geojson = turf.polygon([data]);
and bounding box calculated like this:
const bbox = turf.bbox(geojson);
Modified CodePen

Google Maps Drawing on Mobile loses Draggable

I am trying to use google maps to allow a user to create multiple editabled/draggable polygons. Everything works fine from a desktop browser, but on a mobile/touch device all polygons are no longer draggable once a user adds a new polygon to the map. Polygons loaded on the map during initialize are draggable as expected.
I know touch events are not really supported by the google maps api, but is there a workaround I can do?
Simplified example:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 24.886, lng: -70.268},
mapTypeId: 'terrain'
});
var triangleCoords = [
{lat: 25.774, lng: -80.190},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757},
{lat: 25.774, lng: -80.190}
];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
draggable: true
});
bermudaTriangle.setMap(map);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon']
},
polygonOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
draggable: true,
zIndex: 10000
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
drawingManager.setOptions({
drawingMode: null
});
});
}
google.maps.event.addDomListener(window, 'load', initMap);
https://codepen.io/cyberjus/pen/XEVoer
Upon load from a mobile device, the first polygon is draggable, but once another polygon is drawn, neither can be dragged anymore. I am testing on an actual iPad, so I dont know if it is IOS specific or not.

Check if an address is in one of several polygons

Been a rabid consumer of Stack Overflow for many moons, but this is my first question so bear with me!
I know HTML & CSS but am not very JS literate, nor am I experienced in the Google Maps API.
I want my users to input an address using the Google Maps 'places' library and return a result as to whether or not the lat/long coordinates of that place fall within one of three predetermined polygons on the map.
Based on the location provided, the API would generate one of 3 messages:
If the coordinate is outside all polygons then display msg 1
If the coordinate is inside polygon 1 then display msg 2
If the coordinate is inside either polygon 2 or 3, then display msg 3.
I found this near-perfect-match for my need case which was well answered by MKiss. The JS code is:
var map;
var geocoder; //Added on 27/09/2016
var marker;
var polygon;
var bounds;
window.onload = initMap;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 14,
scaleControl: true
});
geocoder = new google.maps.Geocoder(); //Added on 27/09/2016
bounds = new google.maps.LatLngBounds();
google.maps.event.addListenerOnce(map, 'tilesloaded', function(evt) {
bounds = map.getBounds();
});
marker = new google.maps.Marker({
position: center
});
polygon = new google.maps.Polygon({
path: area,
geodesic: true,
strokeColor: '#FFd000',
strokeOpacity: 1.0,
strokeWeight: 4,
fillColor: '#FFd000',
fillOpacity: 0.35
});
polygon.setMap(map);
var input = /** #type {!HTMLInputElement} */(
document.getElementById('pac-input'));
var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
marker.setMap(null);
var place = autocomplete.getPlace();
var newBounds = new google.maps.LatLngBounds(bounds.getSouthWest(), bounds.getNorthEast()); //Changed
// removed newBounds = bounds;
if (!place.geometry) {
geocodeAddress(input.value);//Added on 27/09/2016
//window.alert("Autocomplete's returned place contains no geometry");
return;
};
marker.setPosition(place.geometry.location);
marker.setMap(map);
newBounds.extend(place.geometry.location);
map.fitBounds(newBounds);
if (google.maps.geometry.poly.containsLocation(place.geometry.location, polygon)){
alert('The area contains the address');
} else {
alert('The address is outside of the area.');
};
});
}
//Added on 27/09/2016
//*************************
function geocodeAddress(addr) {
geocoder.geocode({'address': addr}, function(results, status) {
if (status === 'OK') {
var newBounds = new google.maps.LatLngBounds(bounds.getSouthWest(), bounds.getNorthEast());
marker.setPosition(results[0].geometry.location);
marker.setMap(map);
newBounds.extend(results[0].geometry.location);
map.fitBounds(newBounds);
if (google.maps.geometry.poly.containsLocation(results[0].geometry.location, polygon)){
alert('The area contains the address');
} else {
alert('The address is outside of the area.');
};
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
};
//*************************
var center = new google.maps.LatLng(41.3899621, 2.1469796);
var area= [
{lat: 41.3749971 , lng: 2.1669979},
{lat: 41.3749569 , lng: 2.1683179},
{lat: 41.3759391 , lng: 2.1690059},
{lat: 41.3780967 , lng: 2.1652293},
{lat: 41.3777424 , lng: 2.1645641},
{lat: 41.380383 , lng: 2.1611738},
{lat: 41.3820333 , lng: 2.1634162},
{lat: 41.3837962 , lng: 2.1614313},
{lat: 41.3956283 , lng: 2.1772671},
{lat: 41.4000548 , lng: 2.1715379},
{lat: 41.3973829 , lng: 2.16156},
{lat: 41.3970609 , lng: 2.1603155},
{lat: 41.3981555 , lng: 2.158041},
{lat: 41.3990569 , lng: 2.1534061},
{lat: 41.400924 , lng: 2.1511316},
{lat: 41.4019541 , lng: 2.1492863},
{lat: 41.4015678 , lng: 2.1472263},
{lat: 41.400087 , lng: 2.1439648},
{lat: 41.4014068 , lng: 2.1419048},
{lat: 41.3997651 , lng: 2.1375704},
{lat: 41.3980911 , lng: 2.1330643},
{lat: 41.3957088 , lng: 2.1283007},
{lat: 41.3930689 , lng: 2.1241379},
{lat: 41.3883039 , lng: 2.1270561},
{lat: 41.3882556 , lng: 2.128129},
{lat: 41.3857442 , lng: 2.1296847},
{lat: 41.3831039 , lng: 2.130897},
{lat: 41.3805882 , lng: 2.1322328},
{lat: 41.3769615 , lng: 2.1339547},
{lat: 41.3761192 , lng: 2.1343651},
{lat: 41.3753413 , lng: 2.1350651},
{lat: 41.3751301 , lng: 2.1405369},
{lat: 41.3750193 , lng: 2.1458101},
{lat: 41.3747598 , lng: 2.1521402},
{lat: 41.374651 , lng: 2.1585345},
{lat: 41.3746349 , lng: 2.1606589},
{lat: 41.3747476 , lng: 2.1653795},
{lat: 41.3749971, lng: 2.1669979}
];
But am at a loss as to how to code the logic to deal with all three polygons.
I've constructed the three polygons here.
Thanks in advance for any help!
The following code alert if the address is inside of any of the given polygons.
(Replace YOUR_GOOGLE_KEY with your google key on index.html)
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<input id="js-input" class="map__input" type="text" placeholder="Enter a location">
<div id="js-map" class="map"></div>
<script src="index.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&&key=YOUR_GOOGLE_KEY&callback=initMap" async defer></script>
</body>
</html>
index.css
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
z-index: 1;
}
.map__input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 280px;
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
position: absolute;
top: 50px;
left: 50%;
transform: translateX(-50%);
z-index: 2;
}
index.js
const myPolygons = [
{
name: 'Yellow Area',
path: [ // You have to changes those values with lats and lngs of your polygon
{ lat: 11.0104601, lng: -74.8078690 },
{ lat: 11.0034337, lng: -74.7891669 },
{ lat: 11.022699, lng: -74.80161799 },
],
geodesic: true,
strokeColor: '#FFd000',
strokeOpacity: 1.0,
strokeWeight: 4,
fillColor: '#FFd000',
fillOpacity: 0.35
},
{
name: 'Blue Area',
path: [ // You have to changes those values with lats and lngs of your polygon
{ lat: 11.0194794, lng: -74.8504209 },
{ lat: 11.0131404, lng: -74.8276712 },
{ lat: 10.9946794, lng: -74.8395515 },
],
geodesic: true,
strokeColor: 'blue',
strokeOpacity: 1.0,
strokeWeight: 4,
fillColor: 'blue',
fillOpacity: 0.35
},
{
name: 'Green Area',
path: [ // You have to changes those values with lats and lngs of your polygon
{ lat: 10.9772761, lng: -74.8134354 },
{ lat: 10.9933967, lng: -74.8183852 },
{ lat: 10.987963, lng: -74.78883119 },
],
geodesic: true,
strokeColor: 'green',
strokeOpacity: 1.0,
strokeWeight: 4,
fillColor: 'green',
fillOpacity: 0.35
},
];
function initMap() {
let map;
let marker;
const createMap = ({ latitude, longitude, polygons, mapId, inputId }) => {
const center = new google.maps.LatLng(latitude, longitude);
map = new google.maps.Map(document.getElementById(mapId), { center, zoom: 14, scaleControl: true });
marker = new google.maps.Marker({ position: center });
const createGooglePolygons = ({ name, ...polygon }) => {
const newPolygon = new google.maps.Polygon(polygon);
newPolygon.setMap(map);
return { name, polygon: newPolygon };
}
const googlePolygons = polygons.map(createGooglePolygons);
const input = document.getElementById(inputId);
const autocomplete = new google.maps.places.Autocomplete(input);
const onAutocompleteChange = () => {
const place = autocomplete.getPlace();
const location = place.geometry.location;
const poly = google.maps.geometry.poly;
if (!place.geometry) return alert("Autocomplete's returned place contains no geometry");
marker.setPosition(location);
marker.setMap(map);
const isLocationInsidePolygon = ({ polygon }) => poly.containsLocation(location, polygon);
const matchedPolygon = googlePolygons.find(isLocationInsidePolygon);
if (!matchedPolygon) return alert('The address does not match any valid area');
alert(`The ${matchedPolygon.name} contains the address`);
};
autocomplete.addListener('place_changed', onAutocompleteChange);
}
createMap({
latitude: 10.9939751, //Put your origin latitude here
longitude: -74.8069332, //Put your origin longitude here
polygons: myPolygons,
mapId: 'js-map',
inputId: 'js-input'
})
};
window.onload = initMap;
You just need to define the polygons separately and alter the logic to test for whether the location is within each polygon or both. I am not familiar with javascript but here is an example using you code that should get you started (maybe someone more familiar will tidy it up):
var map;
var marker;
var polygon;
var bounds;
window.onload = initMap;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 14,
scaleControl: true
});
bounds = new google.maps.LatLngBounds();
google.maps.event.addListenerOnce(map, 'tilesloaded', function(evt) {
bounds = map.getBounds();
});
marker = new google.maps.Marker({
position: center
});
polygon1 = new google.maps.Polygon({
path: area1,
geodesic: true,
strokeColor: '#FFd000',
strokeOpacity: 1.0,
strokeWeight: 4,
fillColor: '#FFd000',
fillOpacity: 0.35
});
polygon2 = new google.maps.Polygon({
path: area2,
geodesic: true,
strokeColor: '#00ffe1',
strokeOpacity: 1.0,
strokeWeight: 4,
fillColor: '#00ffe1',
fillOpacity: 0.35
});
polygon1.setMap(map);
polygon2.setMap(map);
var input = /** #type {!HTMLInputElement} */(
document.getElementById('pac-input'));
var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
marker.setMap(null);
var place = autocomplete.getPlace();
var newBounds = new google.maps.LatLngBounds();
newBounds = bounds;
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
};
marker.setPosition(place.geometry.location);
marker.setMap(map);
newBounds.extend(place.geometry.location);
map.fitBounds(newBounds);
if (google.maps.geometry.poly.containsLocation(place.geometry.location, polygon1)){
if (google.maps.geometry.poly.containsLocation(place.geometry.location, polygon2)){
alert('The address is inside polygon1 and 2');
} else {
alert('The address is inside polygon1');
}
} else {
if (google.maps.geometry.poly.containsLocation(place.geometry.location, polygon2)){
alert('The address is inside polygon2');
} else {
alert('The address is outside of the area.');
};
}
});
}
var center = new google.maps.LatLng(41.3899621, 2.1469796);
var area1= [
{lat: 41.3749971 , lng: 2.1669979},
{lat: 41.3749569 , lng: 2.1683179},
{lat: 41.3759391 , lng: 2.1690059},
{lat: 41.3780967 , lng: 2.1652293},
{lat: 41.3777424 , lng: 2.1645641},
{lat: 41.380383 , lng: 2.1611738},
{lat: 41.3820333 , lng: 2.1634162},
{lat: 41.3837962 , lng: 2.1614313},
{lat: 41.3956283 , lng: 2.1772671},
{lat: 41.4000548 , lng: 2.1715379},
{lat: 41.3973829 , lng: 2.16156},
{lat: 41.3970609 , lng: 2.1603155},
{lat: 41.3981555 , lng: 2.158041},
{lat: 41.3990569 , lng: 2.1534061},
{lat: 41.400924 , lng: 2.1511316},
{lat: 41.4019541 , lng: 2.1492863},
{lat: 41.4015678 , lng: 2.1472263}];
var area2= [
{lat: 41.3973829 , lng: 2.16156},
{lat: 41.3970609 , lng: 2.1603155},
{lat: 41.3981555 , lng: 2.158041},
{lat: 41.3990569 , lng: 2.1534061},
{lat: 41.400924 , lng: 2.1511316},
{lat: 41.4019541 , lng: 2.1492863},
{lat: 41.4015678 , lng: 2.1472263},
{lat: 41.400087 , lng: 2.1439648},
{lat: 41.4014068 , lng: 2.1419048},
{lat: 41.3997651 , lng: 2.1375704},
{lat: 41.3980911 , lng: 2.1330643},
{lat: 41.3957088 , lng: 2.1283007},
{lat: 41.3930689 , lng: 2.1241379},
{lat: 41.3883039 , lng: 2.1270561},
{lat: 41.3882556 , lng: 2.128129},
{lat: 41.3857442 , lng: 2.1296847},
{lat: 41.3831039 , lng: 2.130897},
{lat: 41.3805882 , lng: 2.1322328},
{lat: 41.3769615 , lng: 2.1339547},
{lat: 41.3761192 , lng: 2.1343651},
{lat: 41.3753413 , lng: 2.1350651},
{lat: 41.3751301 , lng: 2.1405369},
{lat: 41.3750193 , lng: 2.1458101},
{lat: 41.3747598 , lng: 2.1521402},
{lat: 41.374651 , lng: 2.1585345},
{lat: 41.3746349 , lng: 2.1606589},
{lat: 41.3747476 , lng: 2.1653795},
{lat: 41.3749971, lng: 2.1669979}
];

can't define style on google maps Polygon

I'm trying to add some polygons on data layer. I have defined the colors that they should have. My problem is that I can't set a color for each but if I set the style it becomes like a global style.
My JS FIDDLE
I tried like , with an random color:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: -34.872, lng: 155.252},
});
var innerCoords1 = [
{lat: -33.364, lng: 154.207},
{lat: -34.364, lng: 154.207},
{lat: -34.364, lng: 155.207},
{lat: -33.364, lng: 155.207}
];
var innerCoords2 = [
{lat: -33.364, lng: 156.207},
{lat: -34.364, lng: 156.207},
{lat: -34.364, lng: 157.207},
{lat: -33.364, lng: 157.207}
];
var innerCoords3 = [
{lat: -33.979, lng: 157.987},
{lat: -34.979, lng: 157.987},
{lat: -34.979, lng: 158.987},
{lat: -33.979, lng: 158.987}
];
map.data.add({geometry: new google.maps.Data.Polygon([innerCoords1,
innerCoords2,
innerCoords3])});
map.data.setStyle(function(feature) {return {fillColor: getRandomColor(),strokeWeight: 5}})
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
how can I define style(fill color) for each rectangle to be different and unique, can someone help me please?
Your getRandomColor function isn't giving you different colors because it is only called once. If I assign each Polygon an id and index into an array based on that, I get different colors (I assume you don't really need random colors).
var colorArray = ["#FF0000", "#00FF00", "#0000FF"];
map.data.setStyle(function(feature) {
var color = colorArray[feature.getId()];
return {
fillColor: color,
strokeWeight: 5
}
});
It does work for me if I call it the same as above (outside of the returned style):
map.data.setStyle(function(feature) {
var color = getRandomColor();
return {
fillColor: color,
strokeWeight: 5
}
});
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {
lat: -34.872,
lng: 155.252
},
});
var innerCoords1 = [{
lat: -33.364,
lng: 154.207
}, {
lat: -34.364,
lng: 154.207
}, {
lat: -34.364,
lng: 155.207
}, {
lat: -33.364,
lng: 155.207
}];
var innerCoords2 = [{
lat: -33.364,
lng: 156.207
}, {
lat: -34.364,
lng: 156.207
}, {
lat: -34.364,
lng: 157.207
}, {
lat: -33.364,
lng: 157.207
}];
var innerCoords3 = [{
lat: -33.979,
lng: 157.987
}, {
lat: -34.979,
lng: 157.987
}, {
lat: -34.979,
lng: 158.987
}, {
lat: -33.979,
lng: 158.987
}];
map.data.add({
id: 0,
geometry: new google.maps.Data.Polygon([innerCoords1])
});
map.data.add({
id: 1,
geometry: new google.maps.Data.Polygon([innerCoords2])
});
map.data.add({
id: 2,
geometry: new google.maps.Data.Polygon([innerCoords3])
});
var colorArray = ["#FF0000", "#00FF00", "#0000FF"];
map.data.setStyle(function(feature) {
var color = colorArray[feature.getId()];
return {
fillColor: color,
strokeWeight: 5
}
});
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
console.log(color);
return color;
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Drawing lines on google maps api

I am able to draw the lines on the maps using the following code:
var flightPlanCoordinates1 = [
{ lat: 22.53412218657744, lng: -95.4580076783896 },
{ lat: 25.265810430433756, lng: -96.51269517838955 },
{ lat: 24.308304859959954, lng: -92.4916990846396 },
{ lat: 28.150714091845007, lng: -94.07373033463955 },
{ lat: 26.530793950651773, lng: -89.92089830338955 },
{ lat: 25.5635039073037, lng: -87.63574205338955 },
{ lat: 26.491469591982202, lng: -85.30664049088955 },
{ lat: 28.65323578152034, lng: -86.80078111588955 },
{ lat: 28.845876611067364, lng: -88.91015611588955 },
{ lat: 27.587415049297192, lng: -88.33886705338955 },
{ lat: 25.84068541364038, lng: -94.00781236588955 }
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates1,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
But in a real application as we are getting data from db and populating it , I am not able to get the lines on the map
So, here is the object declaration and initialization:
flightPlanCoordinates = [];
for (var i = 0; i < jsonOut.length; i++) {
jsonCor["lat"] = jsonOut[i]["lat"];
jsonCor["long"] = jsonOut[i]["long"];
flightPlanCoordinates.push(jsonCor);
}
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
The data in the object is as below:
0: Object
lat: 23.222417047162825
long: -95.45800767838955
__proto__: Object
1:Object
so on which is exactly in the example shown above.
What is the problem with the object which is constructed?
You probably need to do this:
for (var i = 0; i < jsonOut.length; i++) {
flightPlanCoordinates.push({
lat: parseFloat(jsonOut[i]["lat"]),
lng: parseFloat(jsonOut[i]["long"]
});
}
Firstly make the structure of your coordinates match what you were doing originally, i.e. {lat: x, lng: y} instead of {lat, x, long: y}.
Secondly because you're reading it from JSON, you probably also need to do parseFloat() on the values, otherwise they're likely to be strings.