I'm trying to display polygons in google map. I have a .xlsx file with a column named "polygon" in which are polygon coordinates in a strange format.
For example: [[], [[-68.0913, -38.95585], [-68.09148, -38.95666], [-68.07378, -38.9591], [-68.0393, -38.96023], [-68.03909, -38.95884], [-68.03909, -38.95517], [-68.03273, -38.95452], [-68.03288, -38.95122], [-68.03322, -38.94787], [-68.04327, -38.94201], [-68.06786, -38.93913], [-68.07294, -38.94037], [-68.07719, -38.94237], [-68.07908, -38.94347], [-68.08127, -38.94434], [-68.08457, -38.94739], [-68.1084, -38.9478], [-68.10842, -38.95442], [-68.0914, -38.9549], [-68.09136, -38.95559], [-68.09123, -38.95594]], [[-68.11045, -38.95312]], [[-68.09643, -38.96523], [-68.0967, -38.95809], [-68.09688, -38.95342], [-68.07472, -38.95842], [-68.04073, -38.95897], [-68.03989, -38.95899], [-68.03897, -38.95901], [-68.0391, -38.96296], [-68.04457, -38.96303], [-68.04461, -38.96304], [-68.04488, -38.97065], [-68.04485, -38.97065], [-68.04489, -38.97132], [-68.05176, -38.97112], [-68.05704, -38.97265], [-68.05725, -38.97858], [-68.06837, -38.97866], [-68.06886, -38.97315], [-68.06901, -38.96554], [-68.07631, -38.96542]]].
Is it possible to build a polygon with this data structure or it's an incorrect format?
Your data is a GeoJSON like coordinates format.
To translate that into a Google Maps Polygon:
// go through the outer array (of polygons)
for (var i = 0; i < coords.length; i++) {
// array for the LatLng coordinates
var polygonCoords = [];
// go through each coordinate in the array.
// GeoJSON is [longitude,latitude]
for (var j = 0; j < coords[i].length; j++) {
var pt = new google.maps.LatLng(coords[i][j][1], coords[i][j][0])
polygonCoords.push(pt);
}
// Construct the polygon.
var polygon = new google.maps.Polygon({
paths: polygonCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map
});
}
}
proof of concept fiddle
code snippet:
// This example creates a simple polygon representing the Bermuda Triangle.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: 24.886,
lng: -70.268
},
mapTypeId: 'terrain'
});
var coords = [[], [[-68.0913, -38.95585], [-68.09148, -38.95666], [-68.07378, -38.9591], [-68.0393, -38.96023], [-68.03909, -38.95884], [-68.03909, -38.95517], [-68.03273, -38.95452], [-68.03288, -38.95122], [-68.03322, -38.94787], [-68.04327, -38.94201], [-68.06786, -38.93913], [-68.07294, -38.94037], [-68.07719, -38.94237], [-68.07908, -38.94347], [-68.08127, -38.94434], [-68.08457, -38.94739], [-68.1084, -38.9478], [-68.10842, -38.95442], [-68.0914, -38.9549], [-68.09136, -38.95559], [-68.09123, -38.95594]], [[-68.11045, -38.95312]], [[-68.09643, -38.96523], [-68.0967, -38.95809], [-68.09688, -38.95342], [-68.07472, -38.95842], [-68.04073, -38.95897], [-68.03989, -38.95899], [-68.03897, -38.95901], [-68.0391, -38.96296], [-68.04457, -38.96303], [-68.04461, -38.96304], [-68.04488, -38.97065], [-68.04485, -38.97065], [-68.04489, -38.97132], [-68.05176, -38.97112], [-68.05704, -38.97265], [-68.05725, -38.97858], [-68.06837, -38.97866], [-68.06886, -38.97315], [-68.06901, -38.96554], [-68.07631, -38.96542]]];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < coords.length; i++) {
var polygonCoords = [];
for (var j = 0; j < coords[i].length; j++) {
var pt = new google.maps.LatLng(coords[i][j][1], coords[i][j][0])
bounds.extend(pt);
polygonCoords.push(pt);
}
// Construct the polygon.
var polygon = new google.maps.Polygon({
paths: polygonCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map
});
}
map.fitBounds(bounds);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
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>
I am loading a data layer in a google map, over a certain country (it's a drawing over a country):
map.data.addGeoJson(geoJsonObject);
I am pretty sure there isn't, but... is there a way to check that the bounds of the map are inside the bounds of the data layer?
(basically, I want to know, when the user navigates on the map, if the current viewport is inside data layer);
var bounds = this.map.getBounds();
var sw = bounds.getSouthWest();
Maybe I can query the data layer in the position of the south west bound and check for some props. indicating that I am inside that data layer?
Or at least:
Does anyone know a way how to get a certain feature object programmatically, knowing the lat and long?
Here the google maps uses events to get to the feature object:
map.data.addListener('click', function(event) {
event.feature.setProperty('isColorful', true);
});
But I do not want to use events. Is there a method to supply the coordinates of a point and get to the feature object?
Something like:
map.getFeature(lat, long).setProperty('isColorful', true);
google.maps.LatLngBounds.contains function could be utilized for that purpose, but since it accepts a single location, the following solution is suggested:
1) initialize data layer bounds from GeoJSON coordinates:
var dataLayer = map.data;
var layerBounds = new google.maps.LatLngBounds();
//1.collect all coordinates from data layer
dataLayer.forEach(function(f) {
var geometry = f.getGeometry();
processCoordinates(geometry, layerBounds.extend, layerBounds);
});
2) determine whether map bounds are within a layer bounds:
if (layerBounds.contains(map.getBounds().getNorthEast()) && layerBounds.contains(map.getBounds().getSouthWest())) {
//...
}
Working example
In the provided example green colored area will be displayed if map
bounds are within a layer bounds, and the red colored in
the opposite case:
var area;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 53.349248,
lng: -6.255323
},
zoom: 6,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
displayDataLayer(map);
document.getElementById("btnShow").onclick = function() {
var result = displayDataLayerBoundsArea(map);
};
}
function displayDataLayer(map) {
var dataLayer = map.data;
dataLayer.loadGeoJson('https://gist.githubusercontent.com/vgrem/440708612b574764c309/raw/2a4e2feadc204806440c51a14c2ef1f54f4fc3d8/Census2011_Province_generalised20m.json');
dataLayer.setMap(map);
}
function displayDataLayerBoundsArea(map) {
var dataLayer = map.data;
var layerBounds = new google.maps.LatLngBounds();
//1.collect all coordinates from data layer
dataLayer.forEach(function(f) {
var geometry = f.getGeometry();
processCoordinates(geometry, layerBounds.extend, layerBounds);
});
if (area != null) {
area.setMap(null);
}
//2.determine whether map bounds are contained within a layer bounds
if (layerBounds.contains(map.getBounds().getNorthEast()) && layerBounds.contains(map.getBounds().getSouthWest())) {
//map.fitBounds(bounds);
area = new google.maps.Rectangle({
strokeColor: '#00FF00',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#00FF00',
fillOpacity: 0.35,
map: map,
bounds: {
north: layerBounds.getNorthEast().lat(),
south: layerBounds.getSouthWest().lat(),
east: layerBounds.getNorthEast().lng(),
west: layerBounds.getSouthWest().lng()
}
});
} else {
//map.fitBounds(bounds);
area = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: {
north: layerBounds.getNorthEast().lat(),
south: layerBounds.getSouthWest().lat(),
east: layerBounds.getNorthEast().lng(),
west: layerBounds.getSouthWest().lng()
}
});
}
}
function processCoordinates(geometry, callback, thisArg) {
if (geometry instanceof google.maps.LatLng) {
callback.call(thisArg, geometry);
} else if (geometry instanceof google.maps.Data.Point) {
callback.call(thisArg, geometry.get());
} else {
geometry.getArray().forEach(function(g) {
processCoordinates(g, callback, thisArg);
});
}
}
#map {
width: 800px;
height: 640px;
}
<button id="btnShow">Show</button>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
JSFiddle
I have requirement such that I need to draw a line between Sydney, Melbourne and Adelaide and the line between Sydney and Adelaide should be dark in color and the line between Melbourne and Adelaide should be lighter.
Is it possible in current API to provide this functionality in a single object:
new google.maps.Polyline({
});
To achieve the functionality?
One option would be to create google.maps.Polyline object per every line, below is provided the modified example from Simple Polylines page:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: -32.9340105, lng: 128.2698231},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var flightPlanCoordinates = [
{lat: -33.877024, lng: 151.227963},
{lat: -37.816567, lng: 144.961489},
{lat: -34.930054, lng: 138.593065}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates.slice(0,2),
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
var flightPath2 = new google.maps.Polyline({
path: flightPlanCoordinates.slice(1,3),
geodesic: true,
strokeColor: '#FFCC00',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
A single polyline has a single set of properties. You can do it with a single google.maps.Polyline for each unique set of properties, so in your example, two polylines.
I've followed the instruction given on the Google Maps API site, but my circle is never being drawn to my map, and I don't really understand what I am missing, could anybody point me in the right direction?
Here is my method to add the new address marker and search radius to the map (Note that the marker is added as expected):
// Add the users point to the map
function addAddress() {
// Get the users current location
var location = document.getElementById("P1_LOCATION").value; // Users postcode
var radius_size = document.getElementById("P1_RADIUS").value; // Users radius size in miles
var search_radius;
// Translate the users location onto the map
geocoder.geocode({ 'address': location}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
// Center around the users location
map.setCenter(results[0].geometry.location);
// Place a marker where the user is situated
var marker = new google.maps.Marker({
map:map,
position: results[0].geometry.location
});
// configure the radius
// Construct the radius circle
var radiusOptions = {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: marker.center, // I want to set the center around the users location
radius: radius_size // I want the radius to be in miles, how do I do this?
};
// add the radius circle to the map
search_radius = new google.maps.Circle(radiusOptions);
}
});
}
And I'm sure someone will ask if I have configured a base map object, this is done in my initializer method:
var geocoder;
var map;
// Create our base map object
function initialize()
{
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0,0);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
How would I go about getting the radius to display around the given point? any suggestiosn would be greatly appreciated.
I get this error with the posted code: Uncaught InvalidValueError: setRadius: not a number
But the real issues was this: center: marker.center, should be center: marker.getPosition(), (a google.maps.Marker doesn't have a "center" property)
working code snippet:
// Add the users point to the map
function addAddress() {
// Get the users current location
var location = document.getElementById("P1_LOCATION").value; // Users postcode
var radius_size = parseFloat(document.getElementById("P1_RADIUS").value); // Users radius size in meters (unless you scale it to miles)
var search_radius;
// Translate the users location onto the map
geocoder.geocode({
'address': location
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// Center around the users location
map.setCenter(results[0].geometry.location);
// Place a marker where the user is situated
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
// configure the radius
// Construct the radius circle
var radiusOptions = {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: marker.getPosition(), // I want to set the center around the users location
radius: radius_size // I want the radius to be in miles, how do I do this?
};
// add the radius circle to the map
search_radius = new google.maps.Circle(radiusOptions);
}
});
}
var geocoder;
var map;
// Create our base map object
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="P1_LOCATION" value="08646" type="text" />
<input id="P1_RADIUS" value="10000" type="text" />
<input id="geocode" value="geocode" type="button" onclick="addAddress()" />
<div id="map" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
For anybody in future who encounters the same problem, make sure you take the extra step which is not demonstrated in the API guide, and that is to set the Map which the radius object belongs too, in my case:
search_radius.setMap(map);
i am new to stackoveflow, can any one help me to how to draw a rectangle using google api v3, i went through some examples on google i got the below code,
function initialize() {
var coachella = new google.maps.LatLng(33.6803003, -116.173894);
var rectangle;
var myOptions = {
zoom: 11,
center: coachella,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
rectangle = new google.maps.Rectangle();
google.maps.event.addListener(map, 'zoom_changed', function() {
// Get the current bounds, which reflect the bounds before the zoom.
var rectOptions = {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map,
bounds: map.getBounds()
};
rectangle.setOptions(rectOptions);
});
}
But, it functions on zoom event(zoom chanages),i want simple with out event,please help me
map.getBounds() may return not the desired bounds when called to early(immediately after the instantiating of the map).
You may use tilesloaded instead
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
/*your code*/
});