Cant load a Geojson file as path in Gmaps - javascript

I am attempting to create a polygon from a GeoJson file and trigger an alert if a marker leaves the area. I am following gmap tutorials and alot of the code i see is as follows:
var path = [[-12.040397656836609,-77.03373871559225],
[-12.040248585302038,-77.03993927003302], [-12.050047116528843,-
77.02448169303511], [-12.044804866577001,-77.02154422636042]];
polygon = map.drawPolygon({
paths: path,
strokeColor: '#BBD8E9',
strokeOpacity: 1,
strokeWeight: 3,
fillColor: '#BBD8E9',
fillOpacity: 0.6
});
map.addMarker({
lat: -12.043333,
lng: -77.028333,
draggable: true,
fences: [polygon],
outside: function(marker, fence) {
alert('This marker has been moved outside of its fence');
}
});
I am trying to use data from a GeoJson file as the path.
I have tried certain lines of code such as:
var path = map.data.loadGeoJson("./js/area.geojson");
But its like the data isnt loading. I am very new to this and would appreciate any feedback, thank you
Updated code:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 53.28, lng: -7.48},
zoom: 10,
});
var path = map.data.loadGeoJson("./js/area.geojson");
polygon = map.drawPolygon({
paths: path,
useGeoJSON: true,
strokeOpacity: 1,
strokeWeight: 3,
fillColor: '#BBD8E9',
fillOpacity: 0.6
});;
map.addMarker({
lat: 53.28,
lng: -7.48,
draggable: true,
fences: [polygon],
outside: function(m, f){
alert('This marker has been moved outside of its fence');
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places&language=en&key=AIzaSyBDv0PtStQ3dOIyBcqUSxChO7TB-CqdeXY&callback=initMap">
</script>
<script type="text/javascript" src="gmaps.js"></script>
error:
typeError: map.drawPolygon is not a function[Learn More]
XML Parsing Error: not well-formed
Location: file:///C:/geo_fencing%20project
/js/area.geojson
Line Number 1, Column 1:
The coordinates in the geojson file are creating a border on the map, and i have used the geojson file in other tests and it is fine. But a marker is not appearing.

Related

How to use GoogleMaps InfoWindow() on a google.maps.Circle?

The InfoWindow is not displayed if I use it in a loop.
Here is an example of how to use it with Marker:
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/infowindow-simple
I made similar but with Circle, code below, as you can see, console.log is working, but the Infowindow isn't.
What am I missing?
function initMap() {
// Map settings, location : Barcelona, Spain
let map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.37, lng: 2.17},
zoom: 15,
mapTypeId: 'roadmap',
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: false,
rotateControl: false,
fullscreenControl: true
});
// Circle distribution data : location, radius, data
let distribution = {
target_garden: {
center: {lat: 41.371400, lng: 2.171942},
population: 1,
data: `<div>Text 01</div>`
},
target_wtc: {
center: {lat: 41.373477, lng: 2.177650},
population: 2,
data: `<div>Text 02</div>`
}
};
// Display 2 red circles on map
let target;
for (target in distribution) {
let circle = new google.maps.Circle({
// colors
strokeColor: '#000',
strokeOpacity: .2,
strokeWeight: 3,
fillColor: '#f00',
fillOpacity: 0.5,
// position
map: map,
center: distribution[target].center,
radius: Math.sqrt(distribution[target].population) * 100,
// settings
draggable: false,
editable: false,
clickable: true
});
let infowindow = new google.maps.InfoWindow({
content: distribution[target].data
});
// Event : on click a circle open infowindow
circle.addListener('click', function () {
infowindow.open(map, circle);
console.log('on');
});
}
}
I expect a click on the red circle to open an InfoWindow.
The problem isn't the loop, it's that you're trying to anchor the InfoWindow to a Circle. This is from the Maps API documentation:
open([map, anchor])
Opens this InfoWindow on the given map. Optionally, an InfoWindow can be associated with an anchor. In the
core API, the only anchor is the Marker class. However, an anchor can
be any MVCObject that exposes a LatLng position property and
optionally a Point anchorPoint property for calculating the
pixelOffset (see InfoWindowOptions).
So, you could extend Circle somehow to make sure it has a position property, or you can set the position of InfoWindow explicitly (and not use anchor):
circle.addListener('click', function () {
infowindow.setPosition(circle.center)
infowindow.open(map);
});

How to get lat long on draggable polygons? [duplicate]

This question already has an answer here:
How can I detect when an editable polygon is modified?
(1 answer)
Closed 4 years ago.
I want to get Lat and Long when I drag or edit polygon. How i can apply event listeners to this polygone so that whenever i edit or drag polygone it should show lat long on console of every point which i edit on polygon.
function initialize() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: {lat: 51.476706, lng: 0},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// create an array of coordinates for a pentagonal polygon
var arrCoords = [
new google.maps.LatLng(51.474821, -0.001935),
new google.maps.LatLng(51.474647, 0.003966),
new google.maps.LatLng(51.477708, 0.004073),
new google.maps.LatLng(51.479753, 0.000468),
new google.maps.LatLng(51.477654, -0.002192)
];
var polygon = new google.maps.Polygon({
editable: true,
paths: arrCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
first make geodesic: true with draggable: true in polygon
When enabling dragging on a polygon or polyline, you should also
consider making the polygon or polyline geodesic, by setting its
geodesic property to true
Ref: https://developers.google.com/maps/documentation/javascript/shapes
insert_at & set_at gonna be called when polyline get edited.
var polygon = new google.maps.Polygon({
editable: true,
paths: arrCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map,
draggable: true,
geodesic: true
});
google.maps.event.addListener(polygon, 'dragend', function(evt){
console.log(evt.latLng.lat() ,'--', evt.latLng.lng() );
});
google.maps.event.addListener(polygon.getPath(), 'insert_at', function(index, obj) {
console.log('Vertex removed from inner path.');
console.log(obj.lat() ,'--', obj.lng() );
});
google.maps.event.addListener(polygon.getPath(), 'set_at', function(index, obj) {
console.log('Vertex moved on outer path.');
console.log(obj.lat() ,'--', obj.lng() );
});

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.

Google maps don't display circles with certain coordinates

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:

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