Google maps don't display circles with certain coordinates - javascript

I have a set of data about earthquakes, which I need to display it on the google map using circles. At first I used marker to make sure maps work properly. Markers was displayed fine. Then I tried to draw circles with certain radius and coordinates the same as markers, unfortunately they wasn't drown. I found google's tutorial for circles with US cities, which works correct.
After some tests I understood that my problem somehow is related with point coordinates. I can't say what exactly wrong with coordinates, because they are object { lat: val, lng: val } and there isn't any errors, circles just aren't displayed.
I made this gist (please don't steal my api key:)) in order to you can see it for yourself. Hope someone has enough experiences in google maps to know that is wrong (looks like there is no other way to understand the problem). I use google maps for the first time.

As advised by geocodezip, if the calculated 'radius' values are too small may be the reason for not drawing the circle.
As per below calculation, radio is calculated as 2 to the power of 3.3 or 2 raised to 3.3 ( magnitude ), which is 9.849 divided by 2 = 4.924 which is the small to plot for a circle I guess.
Calculation:
radius: Math.pow(2, testEvents[event].magnitude) / 2.0
So I have increased the magnitude values to 17.3, 17.4, 15.4, 15.3 for all of the testEvents objects
and now I am able to see the circles for those markers; see the screen shot attached. Fiddle link attached too.
[![<!DOCTYPE html>
<html>
<head>
</head>
<style>
.map {
height: 500px;
}
</style>
<body>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div>
<div class="row">
<div class="col-md-6 map" id="map1"></div>
<div class="col-md-6 map" id="map2"></div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=your_api_key&callback=initMap">
</script>
<script>
var map1;
var map2;
var citymap = {
chicago: {
center: { lat: 41.878, lng: -87.629 },
population: 2714856
},
newyork: {
center: { lat: 40.714, lng: -74.005 },
population: 8405837
},
losangeles: {
center: { lat: 34.052, lng: -118.243 },
population: 3857799
},
vancouver: {
center: { lat: 49.25, lng: -123.1 },
population: 603502
}
};
var testEvents = {
0: {
point: { lat: 85.09, lng: 15.91 },
magnitude: 17.3
},
1: {
point: { lat: 84.22, lng: 2.85 },
magnitude: 17.4
},
2: {
point: { lat: 85.04, lng: 11.79 },
magnitude: 15.4
},
3: {
point: { lat: 85.25, lng: 13.22 },
magnitude: 15.3
}
};
function initMap() {
map1 = new google.maps.Map(document.getElementById('map1'), {
zoom: 2,
center: new google.maps.LatLng(74.370702, 34.767772),
mapTypeId: 'satellite'
});
map2 = new google.maps.Map(document.getElementById('map2'), {
zoom: 2,
center: new google.maps.LatLng(74.370702, 34.767772),
mapTypeId: 'satellite'
});
WriteQuakeEvents();
}
function WriteQuakeEvents() {
for (var city in citymap) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map2,
center: citymap\[city\].center,
radius: Math.sqrt(citymap\[city\].population) * 100
});
}
for (var event in testEvents) {
var marker = new google.maps.Marker({
position: testEvents\[event\].point,
map: map1
});
var circle = new google.maps.Circle({
strokeColor: '#FFFFFF',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.2,
map: map1,
center: testEvents\[event\].point,
radius: Math.pow(2, testEvents\[event\].magnitude) / 2.0
});
}
}
</script>
</div>
</body>
</html>][1]][1]
//Fiddle here:

Related

How to get the GeoJSON of my geofence in Google Maps API?

I tried to create a geofence in Google Maps JavaScript API, and now I want to get the geoJSON of the fence.
I tried the following:
polygon.getMap().data.toGeoJson((data)=>{
console.log(data);
});
polygon.map.data.toGeoJson((data)=>{
console.log(data);
});
... but it only returns empty features of a FeatureCollection.
This is my script:
"use strict";
let fence, map;
function initMap() {
const zerobstacle = {lat: 9.7934792, lng: 118.7300364};
map = new google.maps.Map(document.getElementById("map"), {
zoom: 11,
center: {
lat: zerobstacle.lat,
lng: zerobstacle.lng
},
mapTypeId: "terrain"
});
// Define the LatLng coordinates for the polygon's path.
const fence_coords = [
{
lat: (zerobstacle.lat+1*0.01),
lng: (zerobstacle.lng-10*0.01)
},
{
lat: (zerobstacle.lat-6*0.01),
lng: (zerobstacle.lng+4*0.01)
},
{
lat: (zerobstacle.lat+8*0.01),
lng: (zerobstacle.lng+6*0.01)
},
{
lat: (zerobstacle.lat+1*0.01),
lng: (zerobstacle.lng-10*0.01)
}
];
// Construct the polygon.
fence = new google.maps.Polygon({
paths: fence_coords,
strokeColor: "##FFF71D",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FFF71D",
fillOpacity: 0.35,
editable: true,
});
fence.setMap(map);
}
Thank you!
Data.toGeoJson returns geoJson from objects that have been added to the DataLayer. If you want your polygon in that result, you need to add it to the DataLayer, currently you are adding it to the map.
To add a polygon to the data layer, see the example in the documentation
For your polygon, that would be:
map.data.add({
geometry: new google.maps.Data.Polygon([fence_coords])
});
To export it, use .toGeoJson:
toGeoJson(callback)
Parameters:
callback: function(Object)
Return Value: None
Exports the features in the collection to a GeoJSON object.
Note that .toGeoJson doesn't have a return value, it takes a callback. To log the GeoJson output:
map.data.toGeoJson(function(geoJson){
console.log(geoJson);
});
proof of concept fiddle
logs:
{"type":"FeatureCollection",
"features":[
{"type":"Feature",
"geometry":{
"type":"Polygon",
"coordinates":[[
[118.63003640000001,9.8034792],
[118.77003640000001,9.7334792],
[118.7900364,9.8734792],
[118.63003640000001,9.8034792],
[118.63003640000001,9.8034792]
]]},
"properties":{}
}
]
}
code snippet:
"use strict";
let fence, map;
function initMap() {
const zerobstacle = {
lat: 9.7934792,
lng: 118.7300364
};
map = new google.maps.Map(document.getElementById("map"), {
zoom: 11,
center: {
lat: zerobstacle.lat,
lng: zerobstacle.lng
},
mapTypeId: "terrain"
});
// Define the LatLng coordinates for the polygon's path.
const fence_coords = [{
lat: (zerobstacle.lat + 1 * 0.01),
lng: (zerobstacle.lng - 10 * 0.01)
},
{
lat: (zerobstacle.lat - 6 * 0.01),
lng: (zerobstacle.lng + 4 * 0.01)
},
{
lat: (zerobstacle.lat + 8 * 0.01),
lng: (zerobstacle.lng + 6 * 0.01)
},
{
lat: (zerobstacle.lat + 1 * 0.01),
lng: (zerobstacle.lng - 10 * 0.01)
}
];
console.log(fence_coords);
map.data.add({
geometry: new google.maps.Data.Polygon([fence_coords])
});
map.data.toGeoJson(function(geoJson) {
console.log(JSON.stringify(geoJson));
document.getElementById('geojson').innerHTML = JSON.stringify(geoJson);
});
}
/* 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;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="geojson"></div>
<div id="map"></div>
</body>
</html>

How to remove multiple Circle for google map

I am trying to remove all the 4 circle from google map with a click of a button, but currently I can only remove one circle. Could anyone let me know how I can remove the multiple circle at once with a click of a button. Sorry I am new to this. Thanks in advance.
My code:
<input onclick="removecircle();" type=button value="Remove line">
<input onclick="addcircle();" type=button value="Restore line">
<div id="map"></div>
<script>
var cityCircle;
var citymap = {
chicago: {
center: {lat: 41.878, lng: -87.629},
population: 2714856
},
newyork: {
center: {lat: 40.714, lng: -74.005},
population: 8405837
},
losangeles: {
center: {lat: 34.052, lng: -118.243},
population: 3857799
},
vancouver: {
center: {lat: 49.25, lng: -123.1},
population: 603502
}
};
function initMap() {
// Create the map.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 37.090, lng: -95.712},
mapTypeId: 'terrain'
});
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
}
}
function addcircle(){
cityCircle.setMap(map);
}
function removecircle(){
cityCircle.setMap(null);
}
Image 1
Image 2
You need to keep references to the circles (and the map) in the global scope (where they will be accessible from HTML click listener functions). Then process through all the circles to either add or remove them from the map.
var circles = [];
var map;
function initMap() {
// Create the map.
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 37.090,
lng: -95.712
},
mapTypeId: 'terrain'
});
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
// keep reference to the circle
circles.push(cityCircle);
}
}
function addcircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(map);
}
}
function removecircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(null);
}
}
proof of concept fiddle
code snippet:
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
<input onclick="removecircle();" type=button value="Remove circles">
<input onclick="addcircle();" type=button value="Restore circles">
<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<div id="map"></div>
<script>
var circles = [];
var map;
function initMap() {
// Create the map.
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 37.090,
lng: -95.712
},
mapTypeId: 'terrain'
});
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
circles.push(cityCircle);
}
}
function addcircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(map);
}
}
function removecircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(null);
}
}
google.maps.event.addDomListener(window, 'load', initMap);
var cityCircle;
var citymap = {
chicago: {
center: {
lat: 41.878,
lng: -87.629
},
population: 2714856
},
newyork: {
center: {
lat: 40.714,
lng: -74.005
},
population: 8405837
},
losangeles: {
center: {
lat: 34.052,
lng: -118.243
},
population: 3857799
},
vancouver: {
center: {
lat: 49.25,
lng: -123.1
},
population: 603502
}
};
</script>

Drawing Multiple Polylines in Google Maps JavaScript API

I'm posting this question because most of the questions I found didn't really answer my question and I finally figured it out. Hopefully this will be helpful to someone else in order to clear things up much more quickly.
-EDIT-
I've edited the question in hopes of it being more useful to anyone who comes across this.
-The Question-
I am having trouble loading multiple polylines into google maps. I've tried passing an array to the new google.maps.Polyline function as follows;
var flightPlanCoordinates = [
{ lat: 41.7171899900261, lng: -85.002969973285587 },
{ lat: 41.716339720601695, lng: -85.00356011920411 },
];
var flightPlanCoordinates2 = [
{ lat: 44, lng: -89 },
{ lat: 49, lng: -89 },
];
var arrayOfFlightPlans = [flightPlanCoordinates, flightPlanCoordinates2];
var flightPath = new google.maps.Polyline({
path: arrayOfFlightPlans,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 4,
});
flightPath.setMap(map);
That didn't work and caused the error "InvalidValueError: at index 0: not a LatLng or LatLngLiteral: in property lat: not a number"
My next attempt involved trying a for loop as follows (note the lat lng arrays did not change from the code snippet above);
for (let i = 0; i < 2; i++) {
var flightPath = new google.maps.Polyline({
path: arrayOfFlightPlans,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 4,
id: segID
});
}
flightPath.setMap(map);
This worked but did not provide the results I was hoping for. The lat lng output was the last set of coordinates in my array. What am I doing wrong? Shouldn't the loop establish a new polyline on each iteration of the for loop?
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.713, lng: -85.003},
zoom: 16
});
var flightPlanCoordinates = [
{ lat: 41.7171899900261, lng: -85.002969973285587 },
{ lat: 41.716339720601695, lng: -85.00356011920411 },
{ lat: 41.715420123340095, lng: -85.003969783778473 },
{ lat: 41.713850219112373, lng: -85.0043800221203 },
{ lat: 41.709869880890324, lng: -85.004809740676933 },
{ lat: 41.709570224086633, lng: -85.004860160268152 },
];
var flightPlanCoordinates2 = [
{ lat: 42, lng: -86 },
{ lat: 42, lng: -87},
{ lat: 42, lng: -88 },
{ lat: 43, lng: -88 },
{ lat: 44, lng: -89 },
{ lat: 49, lng: -89 },
];
var arrayOfFlightPlans = [flightPlanCoordinates, flightPlanCoordinates2];
//Loops through all polyline paths and draws each on the map.
for (let i = 0; i < 2; i++) {
var flightPath = new google.maps.Polyline({
path: arrayOfFlightPlans[i],
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 4,
});
flightPath.setMap(map);
}
}
Establish your coordinates and put them into an array. Using a for loop we can establish a new polyline path on each loop. The piece I was missing was that at the end of the for loop, the path needs to be drawn each time as seen below (An admittedly silly mistake but one that I didn't notice until I came into work this morning).
flightPath.setMap(map);
-EDIT-
To provide further explanation, my thinking was that on each iteration of the for loop, a new google.maps.Polyline object was being instantiated and I was correct, but that doesn't mean a new polyline was being drawn on the map. The polyline only gets added to the map when you issue the setMap(map) command as show in the code above. That means, if we want a new polyline from each element in the array, we need to add each polyline to the map on each iteration of the loop.

If statetement inside class

I'm trying to create a map of hospitals using Google Maps API. Radius of circle is number of beds in that hospital. Also, I would like to have different colors for different types of hospitals. That could be done with IF or SWITCH statement, but neither worked. Here I am attaching example with IF statement.
Problem is with the statement if (citymap[city].tip = 1) (commented out below).
I'm sure that the problem is wrong use of function in this place.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Circles</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var citymap = {
KBC_ZAGREB: {
center: {lat: 45.823554, lng: 16.005904},
beds: 1975,
contentString: "KBC ZAGREB, 1975 kreveta",
tip: 1
},
KBC_SPLIT: {
center: {lat: 43.503908, lng: 16.457924},
beds: 1521,
contentString: "KBC SPLIT, 1521 kreveta",
tip: 1
},
KBC_RIJEKA: {
center: {lat: 45.332623, lng: 14.425665},
beds: 1191,
contentString: "KBC RIJEKA, 1192 kreveta",
tip: 1
},
KBC_OSIJEK: {
center: {lat: 45.558230, lng: 18.711740},
beds: 1160,
contentString: "KBC OSIJEK, 1160 kreveta",
tip: 1
},
KBC_SESTRE_MILOSRDNICE: {
center: {lat: 45.815438, lng: 15.953599},
beds: 1207,
contentString: "KBC SESTRE MILOSRDNICE, 1207 kreveta",
tip: 1
},
KB_DUBRAVA: {
center: {lat: 45.834369, lng: 16.035823},
beds: 625,
contentString: "KB DUBRAVA, 625 kreveta",
tip: 2
},
KB_MERKUR: {
center: {lat: 45.820832, lng: 15.997447},
beds: 345,
contentString: "KB MERKUR, 345 kreveta",
tip: 2
},
KB_SVETI_DUH: {
center: {lat: 45.820140, lng: 15.938853},
beds: 554,
contentString: "KB SVETI DUH, 554 kreveta",
tip: 2
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: 45.811076, lng: 15.979270},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var city in citymap) {
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
fillColor: '#FF0000',
// if (citymap[city].tip = 1){
// strokeColor: '#FF0000',
// fillColor: '#FF0000'
// } else if (citymap[city].tip = 2){
// strokeColor: '#3333cc',
// fillColor: '#3333cc'
// },
strokeOpacity: 0.8,
strokeWeight: 2,
fillOpacity: 0.35,
map: map,
position: citymap[city].center,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].beds) * 10
});
var infowindow = new google.maps.InfoWindow({
content: citymap[city].contentString
});
cityCircle.addListener('click', function() {
infowindow.open(map, cityCircle);
});
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap"></script>
</body>
</html>
Single equal = used to assign value, If you want to compare you could use double equals == to compare two values or triple equals === to check also the type of those compared values, in your case you can use double or triple signs :
if(citymap[city].tip == '1')
//OR
if(citymap[city].tip === '1'))
Hope this helps.
Use
if (citymap[city].tip == 1)
to check.

Add new polygon below everything in Google Maps API

I have a Google.Map object with a set of polygons and polylines already being displayed on that.
I want to add a new google.maps.Polygon object that should be displayed below all elements (more or less like a "background" polygon).
I tried to add it with an absurd low zIndex value (-999999), but it still is displayed above all other elements.
This is what I have done so far:
whiteBackground = new google.maps.Polygon({
path: [ {lat:40.1, lng:-97.1},
{lat:40.1, lng:-89.8},
{lat:44.5, lng:-89.8},
{lat:44.5, lng:-97.1} ],
strokeColor: "#FF0000",
fillColor: "#FFFFFF",
strokeOpacity: 1.0,
strokeWeight: 1.5,
fillOpacity: 1.0,
zIndex: -999999
});
// add to map and to list
whiteBackground.setMap(my_map);
Is there a way to force new polygon whiteBackground to have the smallest zIndex value in the Google.Map in which it is going to be add?
Or there is an way to iterate over all current elements in a Google.Map object?
It works if you set the zIndex properties of all the polygons.
proof of concept fiddle (moves smaller polygon above/below larger polygon on click of the button)
code snippet:
// This example creates a simple polygon representing the Bermuda Triangle and a small polygon that starts above it, toggles above/below by clicking the button (large polygon has zIndex=0; small polygon is +/-1.
var map;
var infoWindow;
var poly2;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: 24.886,
lng: -70.268
},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
// Define the LatLng coordinates for the polygon.
var triangleCoords = [{
lat: 25.774,
lng: -80.190
}, {
lat: 18.466,
lng: -66.118
}, {
lat: 32.321,
lng: -64.757
}];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35,
zIndex: 0
});
bermudaTriangle.setMap(map);
var poly2Coords = [{
lat: 26.78484736105119,
lng: -72.24609375
}, {
lat: 27.059125784374068,
lng: -68.8623046875
}, {
lat: 23.926013339487024,
lng: -71.806640625
}];
poly2 = new google.maps.Polygon({
paths: poly2Coords,
strokeColor: '#0000FF',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35,
zIndex: 1
});
poly2.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="info"></div>
<input id="btn" type="button" value="click" onclick="if (poly2.get('zIndex') > 0) poly2.setOptions({zIndex:-1}); else poly2.setOptions({zIndex:1});" />
<div id="map"></div>

Categories

Resources