Google Maps - Looping through array for polyline - javascript

I want to loop through an array of coordinates that I want to use for markers and drawing a line in google maps.
Is there a solution to create the path property with a loop of const locations?
Please check my example below:
const lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: "red",
scale: 4
};
const locations = [
["Tampere", 61.50741562413278, 23.75886761967578, 1, "Termin: xx.xx"],
["Helsinki", 60.219957, 25.196776, 2, "test2"],
["Travemünde", 55.778989, 18.271974, 2, "test3"],
["Stuttgart", 48.7733567672875, 9.174572759931003, 3, "test4"],
["Ludwigsburg", 48.8893286910321, 9.197454231637288, 4, "test5"],
]
const line = new google.maps.Polyline({
path: [
{ lat: locations[0][1], lng: locations[0][2] },
{ lat: 60.219957, lng: 25.196776 },
{ lat: locations[2][1], lng: locations[2][2] },
{ lat: 53.941362, lng: 10.860464 },
{ lat: 48.7733567672875, lng: 9.174572759931003 },
],
strokeColor: "red",
scale: 7,
icons: [
{
icon: lineSymbol,
offset: "100%",
},
],
map: map,
});
By using above code it creates in Google Maps this:
The result

To process your input array and create a polyline in a loop:
var path = [];
for (var i=0; i<locations.length; i++) {
// add to polyline
path.push({lat: locations[i][2], lng: locations[i][1]});
// create marker
new google.maps.Marker({
position: path[path.length-1],
map: map
})
}
const line = new google.maps.Polyline({
path: path,
strokeColor: "red",
scale: 7,
icons: [
{
icon: lineSymbol,
offset: "100%",
},
],
map: map,
});
proof of concept fiddle
(note that the data in your question doesn't match your picture)
code snippet:
// This example creates a 2-pixel-wide red polyline showing the path of
// the first trans-Pacific flight between Oakland, CA, and Brisbane,
// Australia which was made by Charles Kingsford Smith.
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 3,
center: {
lat: 0,
lng: -180
},
mapTypeId: "terrain",
});
const lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: "red",
scale: 4
};
const locations = [
["Tampere", 61.50741562413278, 23.75886761967578, 1, "Termin: xx.xx"],
["Helsinki", 60.219957, 25.196776, 2, "test2"],
["Travemünde", 55.778989, 18.271974, 2, "test3"],
["Stuttgart", 48.7733567672875, 9.174572759931003, 3, "test4"],
["Ludwigsburg", 48.8893286910321, 9.197454231637288, 4, "test5"],
]
var path = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
path.push({
lat: locations[i][2],
lng: locations[i][1]
});
bounds.extend(path[path.length - 1]);
new google.maps.Marker({
position: path[path.length - 1],
map: map
})
}
const line = new google.maps.Polyline({
path: path,
strokeColor: "red",
scale: 7,
icons: [{
icon: lineSymbol,
offset: "100%",
}, ],
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;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Polylines</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>
</html>

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>

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:

How to get the fired marker using event.addListener with Google Map API v3

I have a simple Google Map with some markers added looping on a json object.
I'm trying to add a listener to all of these markers to do a simple action (change the rotation). Markers are added on map and listener is called, but when i click on one of the markers, the action is performed always on the latest added.
How I can get the fired marker? I think that the way is to use the evt parameter of the listener function, but I don't know how.
I watched inside the evt parameter with firebug but without results.
Here is the code:
for(var i in _points){
_markers[i] = new google.maps.Marker({
position: {
lat: parseFloat(_points[i]._google_lat),
lng: parseFloat(_points[i]._google_lon)
},
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
rotation: parseInt(_points[i]._rotation)
},
map: _map,
title: _points[i]._obj_id
});
google.maps.event.addListener(_markers[i], 'click', function(evt){
//console.log(evt);
r = _markers[i].icon.rotation;
_markers[i].setIcon({
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
rotation: r+15
});
});
}
The this inside the click listener function is a reference to the marker:
google.maps.event.addListener(_markers[i], 'click', function(evt){
//console.log(evt);
r = this.getIcon().rotation;
this.setIcon({
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
rotation: r+15
});
});
proof of concept fiddle
code snippet:
function initMap() {
// Create a map and center it on Manhattan.
var _map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: 40.771,
lng: -73.974
}
});
for (var i in _points) {
_markers[i] = new google.maps.Marker({
position: {
lat: parseFloat(_points[i]._google_lat),
lng: parseFloat(_points[i]._google_lon)
},
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
rotation: parseInt(_points[i]._rotation)
},
map: _map,
title: _points[i]._obj_id
});
google.maps.event.addListener(_markers[i], 'click', function(evt) {
r = this.getIcon().rotation;
this.setIcon({
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
rotation: r + 15
});
});
}
}
google.maps.event.addDomListener(window, "load", initMap);
var _markers = [];
var _points = [{
_google_lat: 40.7127837,
_google_lon: -74.0059413,
_obj_id: "A",
_rotation: 0
}, {
_google_lat: 40.735657,
_google_lon: -74.1723667,
_obj_id: "B",
_rotation: 90
}]
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Drawing circles for Polyline in Google maps

So I found this which allows to draw a dashed line, but I want to draw a dashed line with circles. I can't seem to modify the SVG path in Google Chrome developer tools and when I try to use Sketch, its SVG output (see below) doesn't work with Google maps.
"M0.641033737,6.81266823 C1.92338672,8.94131706 4.69065725,9.63151105 6.82190547,8.35425965 C8.95315369,7.07700826 9.64131924,4.3159806 8.35896626,2.18733177 C7.07661328,0.0586829401 4.30934275,-0.63151105 2.17809453,0.645740345 C0.0468463147,1.92299174 -0.641319243,4.6840194 0.641033737,6.81266823 L0.641033737,6.81266823 Z"
https://developers.google.com/maps/documentation/javascript/examples/overlay-symbol-dashed
One option would be to use the built in google.maps.SymbolPath.CIRCLE
code snippet:
// This example converts a polyline to a dashed line, by
// setting the opacity of the polyline to 0, and drawing an opaque symbol
// at a regular interval on the polyline.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {
lat: 20.291,
lng: 153.027
},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
// [START region_polyline]
// Define a symbol using SVG path notation, with an opacity of 1.
var lineSymbol = {
path: google.maps.SymbolPath.CIRCLE,
strokeOpacity: 1,
fillOpacity: 1,
scale: 3
};
// Create the polyline, passing the symbol in the 'icons' property.
// Give the line an opacity of 0.
// Repeat the symbol at intervals of 20 pixels to create the dashed effect.
var line = new google.maps.Polyline({
path: [{
lat: 22.291,
lng: 153.027
}, {
lat: 18.291,
lng: 153.027
}],
strokeOpacity: 0,
icons: [{
icon: lineSymbol,
offset: '0',
repeat: '20px'
}],
map: map
});
// [END region_polyline]
}
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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>

Categories

Resources