Related
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>
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
I've implemented the code seen at:
https://developers.google.com/maps/documentation/roads/inspector.
In each of the examples on this page, the marker animation loops.
How are you supposed to stop the looping so that the icon remains at the end point until more coordinates are fed to it, at which point I'll animate from the last gps coord to the newest gps coord which I just received?
I just don't want to see the course traveled over and over again.
To stop the animation, cancel the setInterval when the icon reaches the end of the polyline.
function animateCircle(polyline) {
var count = 0;
// fallback icon if the poly has no icon to animate
var defaultIcon = [
{
icon: lineSymbol,
offset: '100%'
}
];
handle = window.setInterval(function() {
if ((count+1) == 200)
window.clearInterval(handle);
count = (count + 1) % 200;
var icons = polyline.get('icons') || defaultIcon;
icons[0].offset = (count / 2) + '%';
polyline.set('icons', icons);
}, 20);
}
proof of concept fiddle
code snippet:
/**
* Animate an icon along a polyline
* #param {Object} polyline The line to animate the icon along
*/
function animateCircle(polyline) {
var count = 0;
// fallback icon if the poly has no icon to animate
var defaultIcon = [{
icon: lineSymbol,
offset: '100%'
}];
handle = window.setInterval(function() {
// when reaches end of polyline
if ((count + 1) == 200) {
// cancel the interval timer
window.clearInterval(handle);
// hide the circle
var icons = polyline.get('icons') || defaultIcon;
icons[0].icon.strokeOpacity = 0;
polyline.set('icons', icons);
}
count = (count + 1) % 200;
var icons = polyline.get('icons') || defaultIcon;
icons[0].offset = (count / 2) + '%';
polyline.set('icons', icons);
}, 20);
}
// Icons for markers
var RED_MARKER = 'https://maps.google.com/mapfiles/ms/icons/red-dot.png';
var GREEN_MARKER = 'https://maps.google.com/mapfiles/ms/icons/green-dot.png';
var BLUE_MARKER = 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png';
var YELLOW_MARKER = 'https://maps.google.com/mapfiles/ms/icons/yellow-dot.png';
// URL for places requests
var PLACES_URL = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
// URL for Speed limits
var SPEED_LIMIT_URL = 'https://roads.googleapis.com/v1/speedLimits';
var coords;
/**
* Current Roads API threshold (subject to change without notice)
* #const {number}
*/
var DISTANCE_THRESHOLD_HIGH = 300;
var DISTANCE_THRESHOLD_LOW = 200;
/**
* #type Array<ExtendedLatLng>
*/
var originals = []; // the original input points, a list of ExtendedLatLng
var interpolate = true;
var map;
var placesService;
var originalCoordsLength;
// Settingup Arrays
var infoWindows = [];
var markers = [];
var placeIds = [];
var polylines = [];
var snappedCoordinates = [];
var distPolylines = [];
// Symbol that gets animated along the polyline
var lineSymbol = {
path: google.maps.SymbolPath.CIRCLE,
scale: 8,
strokeColor: '#005db5',
strokeWidth: '#005db5'
};
// Initialize
function initialize() {
// Centre the map on Sydney
var mapOptions = {
center: {
'lat': -33.870315,
'lng': 151.196532
},
zoom: 16
};
// Map object
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Places object
placesService = new google.maps.places.PlacesService(map);
drawSnappedPolyline();
// Draw the polyline for the snapToRoads API response
// Call functions to add markers and infowindows for each snapped
// point along the polyline.
function drawSnappedPolyline(snappedCoords) {
var snappedCoords = [{
lat: -33.87031296432842,
lng: 151.19649532278828,
originalIndex: 0,
interpolated: false
},
{
lat: -33.8702971,
lng: 151.1964966,
interpolated: true
},
{
lat: -33.8702971,
lng: 151.1964966,
interpolated: true
},
{
lat: -33.8700888,
lng: 151.19690029999998,
interpolated: true
},
{
lat: -33.8700888,
lng: 151.19690029999998,
interpolated: true
},
{
lat: -33.869997,
lng: 151.197091,
interpolated: true
},
{
lat: -33.8699822,
lng: 151.1971317,
interpolated: true
},
{
lat: -33.8699669,
lng: 151.1971912,
interpolated: true
},
{
lat: -33.8699669,
lng: 151.1971912,
interpolated: true
},
{
lat: -33.869954,
lng: 151.1972377,
interpolated: true
},
{
lat: -33.8699449,
lng: 151.1972855,
interpolated: true
},
{
lat: -33.86994270100937,
lng: 151.197353292079,
originalIndex: 1,
interpolated: false
},
{
lat: -33.8699414,
lng: 151.19739339999998,
interpolated: true
},
{
lat: -33.8699441,
lng: 151.1974702,
interpolated: true
},
{
lat: -33.8699507,
lng: 151.19755139999998,
interpolated: true
},
{
lat: -33.8699602,
lng: 151.1976302,
interpolated: true
},
{
lat: -33.86997848255702,
lng: 151.19772949764274,
originalIndex: 2,
interpolated: false
},
{
lat: -33.869981300000006,
lng: 151.19774479999998,
interpolated: true
},
{
lat: -33.8700129,
lng: 151.1978469,
interpolated: true
},
{
lat: -33.8700129,
lng: 151.1978469,
interpolated: true
},
{
lat: -33.8700458,
lng: 151.1979242,
interpolated: true
},
{
lat: -33.8700834,
lng: 151.1979993,
interpolated: true
},
{
lat: -33.8701059,
lng: 151.1980374,
interpolated: true
},
{
lat: -33.870184300000005,
lng: 151.1981381,
interpolated: true
},
{
lat: -33.8702143,
lng: 151.1981743,
interpolated: true
},
{
lat: -33.8702143,
lng: 151.1981743,
interpolated: true
},
{
lat: -33.8702902,
lng: 151.19825269999998,
interpolated: true
},
{
lat: -33.87031617902999,
lng: 151.19827540632983,
originalIndex: 3,
interpolated: false
},
{
lat: -33.8703672,
lng: 151.19832,
interpolated: true
},
{
lat: -33.870480199999996,
lng: 151.19839969999998,
interpolated: true
},
{
lat: -33.870480199999996,
lng: 151.19839969999998,
interpolated: true
},
{
lat: -33.8705388,
lng: 151.1984269,
interpolated: true
},
{
lat: -33.87057888561142,
lng: 151.19844125817298,
originalIndex: 4,
interpolated: false
},
{
lat: -33.870625219935086,
lng: 151.19845785457534,
originalIndex: 5,
interpolated: false
},
{
lat: -33.8706823,
lng: 151.1984783,
interpolated: true
},
{
lat: -33.8706823,
lng: 151.1984783,
interpolated: true
},
{
lat: -33.870718800000006,
lng: 151.1984865,
interpolated: true
},
{
lat: -33.8708181,
lng: 151.19850399999999,
interpolated: true
},
{
lat: -33.8708644,
lng: 151.1985081,
interpolated: true
},
{
lat: -33.870908899999996,
lng: 151.1985078,
interpolated: true
},
{
lat: -33.87095031058638,
lng: 151.19850565885983,
originalIndex: 7,
interpolated: false
},
{
lat: -33.8709998,
lng: 151.19850309999998,
interpolated: true
},
{
lat: -33.87103822739919,
lng: 151.1984996185936,
originalIndex: 8,
interpolated: false
},
{
lat: -33.8713497,
lng: 151.1984714,
interpolated: true
},
{
lat: -33.8713497,
lng: 151.1984714,
interpolated: true
},
{
lat: -33.8718054,
lng: 151.1984326,
interpolated: true
},
{
lat: -33.8719381,
lng: 151.1984352,
interpolated: true
},
{
lat: -33.87203169684805,
lng: 151.198429447748,
originalIndex: 9,
interpolated: false
}
];
var snappedPolyline = new google.maps.Polyline({
path: snappedCoords,
strokeColor: '#005db5',
strokeWeight: 6,
icons: [{
icon: lineSymbol,
offset: '100%'
}]
});
snappedPolyline.setMap(map);
animateCircle(snappedPolyline);
polylines.push(snappedPolyline);
var placeIds = [
"ChIJS6cYMjeuEmsRVxRklOwdF8o",
"ChIJS6cYMjeuEmsRVxRklOwdF8o",
"ChIJ-dDXMDeuEmsRSUxWOfxOpYA",
"ChIJ-dDXMDeuEmsRSUxWOfxOpYA",
"ChIJKVpuODeuEmsRjffu1J1v888",
"ChIJKVpuODeuEmsRjffu1J1v888",
"ChIJKVpuODeuEmsRjffu1J1v888",
"ChIJKVpuODeuEmsRjffu1J1v888",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJR6yfRDeuEmsRhllVwX6TMJ8",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJrV1uWzeuEmsR2N5RA6d2SEE",
"ChIJeUaSWTeuEmsRGB2FlgUyPzE",
"ChIJeUaSWTeuEmsRGB2FlgUyPzE",
"ChIJeUaSWTeuEmsRGB2FlgUyPzE",
"ChIJeUaSWTeuEmsRGB2FlgUyPzE",
"ChIJeUaSWTeuEmsRGB2FlgUyPzE",
"ChIJOU6hVzeuEmsRlJsTGD1vpqU",
"ChIJOU6hVzeuEmsRlJsTGD1vpqU",
"ChIJOU6hVzeuEmsRlJsTGD1vpqU",
"ChIJOU6hVzeuEmsRlJsTGD1vpqU",
"ChIJOU6hVzeuEmsRlJsTGD1vpqU",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJmRMQVTeuEmsRUH-faYDgJs0",
"ChIJ9SmzqTCuEmsRbkJlaklnr2s",
"ChIJ9SmzqTCuEmsRbkJlaklnr2s",
"ChIJ9SmzqTCuEmsRbkJlaklnr2s",
"ChIJ9SmzqTCuEmsRbkJlaklnr2s"
];
for (var i = 0; i < snappedCoords.length; i++) {
var marker = addMarker(snappedCoords[i]);
}
}
} // End init function
// Call the initialize function once everything has loaded
google.maps.event.addDomListener(window, 'load', initialize);
/**
* Add a marker to the map and check for special 'interpolated'
* and 'unsnapped' properties to control which colour marker is used
* #param {ExtendedLatLng} coords - Coords of where to add the marker
* #return {!Object} marker - the marker object created
*/
function addMarker(coords) {
var marker = new google.maps.Marker({
position: coords,
title: coords.lat + ',' + coords.lng,
map: map,
opacity: 0.5,
icon: RED_MARKER
});
// Coord should NEVER be interpolated AND unsnapped
if (coords.interpolated) {
marker.setIcon(BLUE_MARKER);
} else if (!coords.related) {
marker.setIcon(YELLOW_MARKER);
} else if (coords.originalIndex != undefined) {
marker.setIcon(RED_MARKER);
addCorrespondence(coords, marker);
} else {
marker.setIcon({
url: GREEN_MARKER,
scaledSize: {
width: 20,
height: 20
}
});
addCorrespondence(coords, marker);
}
// Make markers change opacity when the mouse scrubs across them
marker.addListener('mouseover', function(mevt) {
marker.setOpacity(1.0);
});
marker.addListener('mouseout', function(mevt) {
marker.setOpacity(0.5);
});
coords.marker = marker; // Save a reference for easy access later
markers.push(marker);
return marker;
}
/**
* Fit the map bounds to the current set of markers
* #param {Array<Object>} markers Array of all map markers
*/
function fitBounds(markers) {
var bounds = new google.maps.LatLngBounds;
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
font-family: Roboto, Noto, sans-serif;
}
#map {
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry">
</script>
<div id="map">
</div>
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}
];
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>