Google Maps & Turf.js Polyline Integration - javascript

I am working on an example google maps and turf js integration. I added the line with GeoJson data.Working snippet is attached. But I want to create a polyline out of turf line positions.
for (var j = 0; j < line.geometry.coordinates.length; j++) {
var wp = new google.maps.LatLng(line.geometry.coordinates[j][1], line.geometry.coordinates[j][0])
path.push(wp);
}
I tried to create a path then create my polyline based on this path but couldn't manage to create a path out of turf line arrays.
Any ideas how can I do this?
Thanks in advance!
var path = [];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
maxZoom: 8,
minZoom: 1,
center: {
lat: 0,
lng: -180
},
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var line = {
"type": "Feature",
"properties": { "line": "on" },
"geometry": {
"type": "LineString",
"coordinates": [
[-122.214, 37.772],
[-157.821, 21.291],
[178.431, -18.142],
[153.027, -27.467]
]
}
};
map.data.addGeoJson(line);
var point = turf.point([185.431, -4.542]);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(point.geometry.coordinates[1], point.geometry.coordinates[0]),
map: map,
});
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://npmcdn.com/#turf/turf#4.7.2/turf.min.js"></script>
<div id="map"></div>

You need to create a polyline and add it to the map:
var polyline = new google.maps.Polyline({
path: path
});
polyline.setMap(map);

I solved it, I just didn't see it...
$.each(line.geometry.coordinates, function (key) {
var wp = { lat: line.geometry.coordinates[key][1], lng: line.geometry.coordinates[key][0] }
path.push(wp);
});

Related

Google Maps - Looping through array for polyline

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>

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>

google maps addGeoJson from text field with js

I am trying to insert an polygon to a google map. The Coordinates for the polygon are in a Textfield value stored like this :
{"type":"Polygon","coordinates":[[[9.99893181141,53.7746888818],[9.53475944814,53.5745692488],[9.94125358875,53.3636652005],[10.4136656981,53.5223496849],[10.3285216551,53.7860492252],[10.1966857177,53.7892944727],[9.99893181141,53.7746888818]]]}
I know I can load geojson files into the map with map.data.addGeoJson(geoJson); but I am unable to format the value the right way (with js).
I am searching an solution like this:
textfieldvalue = document.getElementById('mytextfield').value;
// if nessesary convert textfield to geojson. How to convert
convertettextfield = howtoconvert;
//I dont know if its right like this?
var geoJson = {
"type": "FeatureCollection",
"features": [
"type": "Feature",
"geometry": {
},
"properties": {}
]
};
//add convertettextfield to geoJson. How?
geoJson.howtoputitintogeometry(convertettextfield);
map.data.addGeoJson(geoJson);
To convert text to JSON, use JSON.parse.
<input id="polyJson" type="text" value='{"type":"Polygon","coordinates":[[[9.99893181141,53.7746888818],[9.53475944814,53.5745692488],[9.94125358875,53.3636652005],[10.4136656981,53.5223496849],[10.3285216551,53.7860492252],[10.1966857177,53.7892944727],[9.99893181141,53.7746888818]]]}' />
var polyJson_txt = document.getElementById('polyJson').value;
var polygonJson = JSON.parse(polyJson_txt);
geoJson.features[0].geometry = polygonJson;
code snippet:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var geoJson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {},
"properties": {}
}]
};
geoJson.features[0].geometry = JSON.parse(document.getElementById('polyJson').value);
map.data.addListener('addfeature', function(evt) {
var bounds = new google.maps.LatLngBounds();
var coords = evt.feature.getGeometry().getAt(0).getArray();
for (var i = 0; i < coords.length; i++) {
bounds.extend(coords[i]);
}
map.fitBounds(bounds);
});
map.data.addGeoJson(geoJson);
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function() {
geoJson.features[0].geometry = JSON.parse(document.getElementById('polyJson2').value);
map.data.addGeoJson(geoJson);
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
<input id="polyJson" type="text" value='{"type":"Polygon","coordinates":[[[9.99893181141,53.7746888818],[9.53475944814,53.5745692488],[9.94125358875,53.3636652005],[10.4136656981,53.5223496849],[10.3285216551,53.7860492252],[10.1966857177,53.7892944727],[9.99893181141,53.7746888818]]]}'
/>;
<input id="polyJson2" type="text" value='{"type": "Polygon","coordinates": [[[35.188327,31.699929,0],[35.187895,31.699669,0],[35.187014,31.699729,0],[35.186867,31.700016,0],[35.186783,31.700395,0],[35.186921,31.700787,0],[35.187232,31.701291,0],[35.18763,31.701844,0],[35.187442,31.702328,0],[35.18692,31.702779,0],[35.187064,31.703654,0],[35.187433,31.703794,0],[35.188155,31.70344,0],[35.188921,31.702917,0],[35.189348,31.702887,0],[35.189828,31.70302,0],[35.190313,31.703443,0],[35.190359,31.704104,0],[35.190224,31.704348,0],[35.189797,31.704585,0],[35.189753,31.704948,0],[35.189847,31.705107,0],[35.190187,31.705015,0],[35.190604,31.705041,0],[35.190931,31.705171,0],[35.191435,31.70526,0],[35.191861,31.705231,0],[35.192482,31.705008,0],[35.192945,31.704893,0],[35.193564,31.704449,0],[35.192869,31.704004,0],[35.192256,31.703737,0],[35.191754,31.703371,0],[35.191306,31.703001,0],[35.190838,31.702632,0],[35.190546,31.70221,0],[35.190348,31.701739,0],[35.190323,31.701589,0],[35.189814,31.701624,0],[35.189443,31.701456,0],[35.189108,31.701217,0],[35.188509,31.700359,0],[35.188327,31.699929,0]]]}'
/>
<input id="btn" type="button" value="poly2" />

Google Maps API V3: Exclude single marker from clustering

I am using the google maps api and using grid clustering for the markers. I wanted to know if there is a way to exclude a single marker from clustering. I want a "You are here" marker that is always visible. I tried using a different array for just that marker and not including it the cluster function but that didn't work.
Does anyone have a solution for this?
Here is how i am doing the clustering
$(document).on('click', '#mapbut', function() {
var items, distances, you_are_here = [], markers_data = [], markers_data2 = [], fred, clust1, markss;
you_are_here.push({
lat : Geo.lat,
lng : Geo .lng,
animation: google.maps.Animation.DROP,
title : 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
infoWindow: {
content: '<p>You are Here</p>'
}
});
function loadResults (data) {
if (data.map.length > 0) {
items = data.map;
for (var i = 0; i < items.length; i++)
{
var item = items[i];
var distances = [];
var dist2;
if (item.Lat != undefined && item.Lng != undefined)
{
markers_data.push({
lat : item.Lat,
lng : item.Lng,
title : item.Site,
infoWindow: {
content: '<p>' + item.Site + '</p><p>' + Math.round(item.distance) + ' miles away</p>'
}
});
}
}
}
map.addMarkers(markers_data);
map = new GMaps({
el: '#map',
lat: Geo.lat,
lng: Geo.lng,
zoom: 10,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
markerClusterer: function(map) {
options = {
gridSize: 50
}
clust1 = new MarkerClusterer(map,[], options);
return clust1;
},
scaleControl: true,
streetViewControl: false
});
map.addMarkers(you_are_here);
The GMaps clusters all the markers you add to it with the addMarker method (if you provide a MarkerClusterer).
One option: add your "special" marker (the one that you don't want clustered) to the map manually, so it isn't added to the MarkerClusterer:
The GMaps.map property is a reference to the Google Maps Javascript API v3 map object. So this will add a marker to the map without letting the GMaps library know about it:
you_are_here = new google.maps.Marker({
position: {lat: Geo.lat,lng: Geo.lng},
animation: google.maps.Animation.DROP,
title: 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
map: map.map
});
proof of concept fiddle
code snippet:
var Geo = {
lat: 40.7281575,
lng: -74.07764
};
$(document).on('click', '#mapbut', function() {
var items, distances, you_are_here = [],
markers_data = [],
markers_data2 = [],
fred, clust1, markss;
function loadResults(data) {
if (data.map.length > 0) {
items = data.map;
for (var i = 0; i < items.length; i++) {
var item = items[i];
var distances = [];
var dist2;
if (item.Lat != undefined && item.Lng != undefined) {
markers_data.push({
lat: item.Lat,
lng: item.Lng,
title: item.Site,
infoWindow: {
content: '<p>' + item.Site + '</p><p>' + Math.round(item.distance) + ' miles away</p>'
}
});
}
}
}
map = new GMaps({
el: '#map',
lat: Geo.lat,
lng: Geo.lng,
zoom: 8,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
markerClusterer: function(map) {
options = {
gridSize: 50,
imagePath: "https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m"
}
clust1 = new MarkerClusterer(map, [], options);
return clust1;
},
scaleControl: true,
streetViewControl: false
});
map.addMarkers(markers_data);
you_are_here = new google.maps.Marker({
position: {
lat: Geo.lat,
lng: Geo.lng
},
animation: google.maps.Animation.DROP,
title: 'Your are here',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
infoWindow: {
content: '<p>You are Here</p>'
},
map: map.map
});
// map.addMarkers(you_are_here);
}
loadResults(data);
});
var data = {
map: [{
Lat: 40.7127837,
Lng: -74.005941,
Site: "New York, NY",
distance: 1
}, {
Site: "Newark, NJ",
Lat: 40.735657,
Lng: -74.1723667,
distance: 2
}]
};
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://rawgit.com/HPNeo/gmaps/master/gmaps.js"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/src/markerclusterer.js"></script>
<input id="mapbut" type="button" value="map" />
<div id="map"></div>
To get around this is relatively simple, just after I send the markers array to MarkerClusterer I then add my location.
// Setup cluster markers
var markerCluster = new MarkerClusterer( gmap.map, options )
// add my location
gmap.addMarker({
lat: data.latitude,
lng: data.longitude
...
})
Thanks

Trying to plot the markers on google map using GeoJSON

I am trying to print markers on "google maps" using "geojson" for a given input coordinates.Below attached is the JSON file.
{
"type": "FeatureCollection",
"features":[{
"type":"Feature",
"geometry":
{
"type":"Point",
"coordinates":[-117.7431667,35.9595,0.01]
}
}
]
My Specific problem is i got 3 parameters in the "coordinates" section present.I have referred to couple of examples where the "coordinates" have got two parameters.
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('mapDisplay'), {
zoom: 8,
center: new google.maps.LatLng(44.5403, -78.5463),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
$("#button3").click(function(){
$.get("http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-10-14&endtime=2015-10-21",
function(data,status){
console.info("test");
$.each(data.features, function (i, obj) {
$.each(obj.geometry, function (ind, obj) {
if(ind=="coordinates")
console.log("key:" + ind + " value:" + obj);
var coords = obj;
var latLng = new google.maps.LatLng(coords[2],coords[1],coords[0]);
var marker = new google.maps.Marker
({
position: latLng,
icon: iconBase + 'schools_maps.png',
map: map
});
});
});
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
});
</script>
<body>
<div id="mapDisplay">
</div>
<div id="button_Display">
<button id="button1">Sesimic Events last week</button>
</div>
<div id="Sesimic_Events">
<button id="button2">Places affected</button>
</div>
<div id="markers">
<button id="button3">GoogleMarkers</button>
</div>
<div id="result">
</div>
Any help would be highly appreciated.
Below attached is the screenshot of the output i got when i ran "googlemarkers" button
I think you overcomplicate this task. Read about the GeoJSON Detail Format here -> http://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson_detail.php
Each item of the features section of the JSON response is always on the format :
{
type: "Feature",
properties: {
//a LOT of properties ...
},
geometry: {
type: "Point",
coordinates: [
longitude, //<-- you need this
latitude, //<-- and this
depth
]
},
id: String
}
So plotting the earthquake markers is straight forward :
$.get("http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-10-14&endtime=2015-10-21", function(data,status){
var latLng, marker;
$.each(data.features, function(i, obj) {
latLng = new google.maps.LatLng(
parseFloat(obj.geometry.coordinates[1]),
parseFloat(obj.geometry.coordinates[0])
)
marker = new google.maps.Marker({
position: latLng,
map: map
})
})
})
your code simplified and working here -> http://jsfiddle.net/9p9pk3je/
For loading and parsing GeoJSON data you could utilize Data API, the following example demonstrates how to load GeoJSON data and place markers:
Example
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
});
map.data.addListener('addfeature', function (o) {
setMarker(map, o.feature);
});
map.data.loadGeoJson("http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-10-14&endtime=2015-10-21");
}
function setMarker(map, feature) {
var latLng = feature.getGeometry().get();
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&libraries=drawing&callback=initMap"
async defer></script>

Categories

Resources