google maps addGeoJson from text field with js - javascript

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" />

Related

Google Maps & Turf.js Polyline Integration

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);
});

Add infowindow and custom icon to Google map using Geojson

I have this simple Google map in a Web2py application.
I would like to apply something like a switch for choosing the feature icon and also setting an infoWindow from json text.
Someone knows how I can do it?
var map;
function initMap() {
map = new google.maps.Map(document.getElementById("events_map"), {
center: {lat: 45.070309, lng: 7.686580999999933},
zoom: 13,
mapTypeControl: false
});
var largeInfowindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'idle', function() {
var ne = map.getBounds().getNorthEast();
var north = ne.lat();
var east = ne.lng();
var sw = map.getBounds().getSouthWest();
var south = sw.lat();
var west = sw.lng();
var queryString = '?east=' + east + '&west=' + west + '&south=' + south + '&north=' + north + '&zoom=8'
map.data.loadGeoJson('{{=URL('f_ajax', 'get_locations_g')}}' + queryString);
});
}
json data has a category field that can have 1, 2, 3, or 4 as value.
So with a switch I would like to set the icon in this way:
var icon;
switch (feature.properties.category) {
case '1':
icon = greenIcon;
break;
case '2':
icon = bluIcon;
break;
case '3':
icon = redIcon;
break;
case '4':
icon = blackIcon;
break;
}
But I don't know how.
For the infowindow, can I use this function and how for displaying the json field 'description'?
Thanks.
function populateInfoWindow(marker, infowindow) {
// Check to make sure the infowindow is not already opened on this marker.
if (infowindow.marker != marker) {
infowindow.marker = marker;
infowindow.setContent("<div><a href='" + marker.link + "'>" + marker.title + '</a></div>');
infowindow.open(map, marker);
// Make sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick', function() {
infowindow.marker = null;
});
}
}
For the icon you have to use the setStyle-function.
A object with the icons should be the easiest approach here
map.data.setStyle(function(feature) {
return {
icon:({1:greenIcon,
2:redIcon,
3:blueIcon,
4:blackIcon})[feature.getProperty('category')]
};
});
The function for the InfoWindow may not be used, because there is no marker available in the click-handler, you have to set the options of the InfoWindow based on the clicked feature
map.data.addListener('click', function(event) {
largeInfowindow.setOptions({
map : map,
position: event.feature.getGeometry().get(),
content : '<strong>'+event.feature.getProperty('description')+'</strong>'
})
});
Demo:
function initMap() {
var greenIcon = 'http://maps.gstatic.com/mapfiles/markers2/icon_green.png',
redIcon = 'http://maps.gstatic.com/mapfiles/markers2/marker.png',
blueIcon = 'http://maps.gstatic.com/mapfiles/markers2/boost-marker-mapview.png',
blackIcon = 'http://maps.gstatic.com/mapfiles/markers2/drag_cross_67_16.png',
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat:52.41, lng: 9.74}
}),
largeInfowindow = new google.maps.InfoWindow({pixelOffset:new google.maps.Size(0,-30)});
map.data.setStyle(function(feature) {
return {
icon:({1:greenIcon,
2:redIcon,
3:blueIcon,
4:blackIcon})[feature.getProperty('category')]
};
});
map.data.addListener('click', function(event) {
largeInfowindow.setOptions({
map : map,
position: event.feature.getGeometry().get(),
content : '<strong>'+event.feature.getProperty('description')+'</strong>'
})
});
map.data.addGeoJson(json);
}
var json={
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {category:1,description:'Berlin'},
"geometry": {
"type": "Point",
"coordinates": [
13.392333984375,
52.53627304145948
]
}
},
{
"type": "Feature",
"properties": {category:2,description:'Hamburg'},
"geometry": {
"type": "Point",
"coordinates": [
10.008544921875,
53.57293832648609
]
}
},
{
"type": "Feature",
"properties": {category:3,description:'Cologne'},
"geometry": {
"type": "Point",
"coordinates": [
6.954345703125,
50.951506094481545
]
}
}
]
};
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
<div id="map"></div>

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>

Using Javascript to extract the Latitude and Longitude from a kml field in a Google fusion table

I have a google fusion table that I am inserting data into that contains kml.
I need to query (or extract) the latitude and longitude from the kml column.
When I query the table I get data returned in this format:
{
"kind": "fusiontables#sqlresponse",
"columns": [
"description",
"name",
"geometry"
],
"rows": [
[
"\u003cimg alt=\"The North Fields\" class=\" tall\" src=\"https://d15mj6e6qmt1na.cloudfront.net/files/images/1501/0978/The_North_Fields_small.JPG\" style=\"float:left; padding: 0 3px 3px\" /\u003e\n by ctipp\u003cbr/\u003e\n \u003ca href=\"http://audioboom.com/boos/3260713-coastal-lagoon\"\u003eVisit on audioboom.com\u003c/a\u003e\n \u003chr style=\"clear:both\"/\u003e",
"Coastal Lagoon",
{
"geometry": {
"type": "Point",
"coordinates": [
-0.749484,
50.7627,
0.0
]
}
}
]
]
}
the above data is read into a javascript variable using a callback function and i need to know the correct syntax for extracting the latitude and longitude (ie -0.749484, 50.7627)
I've got this far:
success: function(data) {
var rows = data['rows'];
var desc = rows[0][0];
var name = rows[0][1];
but I'm stuck on the geometry field...
success: function(data) {
var rows = data['rows'];
var desc = rows[0][0];
var name = rows[0][1];
var latitude = rows[0][2].geometry.coordinates[1]; // KML is longitude, latitude
var longitude = rows[0][2].geometry.coordinates[0];
var data = {
"kind": "fusiontables#sqlresponse",
"columns": [
"description",
"name",
"geometry"
],
"rows": [
[
"\u003cimg alt=\"The North Fields\" class=\" tall\" src=\"https://d15mj6e6qmt1na.cloudfront.net/files/images/1501/0978/The_North_Fields_small.JPG\" style=\"float:left; padding: 0 3px 3px\" /\u003e\n by ctipp\u003cbr/\u003e\n \u003ca href=\"http://audioboom.com/boos/3260713-coastal-lagoon\"\u003eVisit on audioboom.com\u003c/a\u003e\n \u003chr style=\"clear:both\"/\u003e",
"Coastal Lagoon", {
"geometry": {
"type": "Point",
"coordinates": [-0.749484,50.7627,0.0]
}
}
]
]
};
function initialize() {
var infowindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: {
lat: 50.7627,
lng: -0.749484
}
});
var latLng = new google.maps.LatLng(data.rows[0][2].geometry.coordinates[1],
data.rows[0][2].geometry.coordinates[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
google.maps.event.addListener(marker, 'click', function(evt) {
infowindow.setContent("name: " + data.rows[0][1] + "<br>desc: " + data.rows[0][0]);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

add infoWindow to map marker using json

I have a simple script that adds a markers on a map, data have been taken from json. I want to add a basic infoWindow to all markers, so that when you click on it, it says "Cartier".
Could you tell me what i'm doing wrong with InfoWindow code?
The code is below.
<!DOCTYPE html>
<html>
<head>
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 2,
center: {lat: 37.275, lng: 22.549},
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Create a <script> tag and set the USGS URL as the source.
var script = document.createElement('script');
script.src = 'http://pastebin.com/raw.php?i=7X956uB3';
document.getElementsByTagName('head')[0].appendChild(script);
map.data.setStyle(function(feature) {
var jstores = feature.getProperty('jstores');
return {
icon: getCircle(jstores),
title: (jstores)
};
});
var contentString = '<div id="content">Cartier</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
function getCircle(jstores) {
var circle = {
path: google.maps.SymbolPath.CIRCLE,
fillColor: 'red',
fillOpacity: .2,
scale: Math.sqrt(jstores) * 2,
strokeColor: 'white',
strokeWeight: .5
};
return circle;
}
function jewellery_stores(results) {
map.data.addGeoJson(results);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Sample JSON:
jewellery_stores({ "type": "FeatureCollection","features": [
{"type": "Feature","geometry": {"type": "Point", "coordinates": [139.730407, 35.70883]},"properties": {"jstores": 106 }},
{"type": "Feature","geometry": {"type": "Point", "coordinates": [37.615556, 55.752222]},"properties": {"jstores": 94 }},
{"type": "Feature","geometry": {"type": "Point", "coordinates": [2.3524282, 48.8564528]},"properties": {"jstores": 89 }},
{"type": "Feature","geometry": {"type": "Point", "coordinates": [55.277067, 25.176594]},"properties": {"jstores": 66 }},
{"type": "Feature","geometry": {"type": "Point", "coordinates": [-0.1276597, 51.5072759]},"properties": {"jstores": 64 }},
{"type": "Feature","geometry": {"type": "Point", "coordinates": [114.169551, 22.285261]},"properties": {"jstores": 63 }}]
Thank you in advance,
Andrey
You are using the Google Maps Javascript API v3 Data Layer
That supports click listeners which allow you to open infowindows containing properties included in the JSON.
map.data.addListener('click', function (e) {
infowindow.setPosition(e.latLng);
infowindow.setContent("hello world<br>jstores="+e.feature.getProperty("jstores")+"<br>"+e.latLng.toUrlValue(6));
infowindow.open(map);
});
Working code snippet:
var map;
var infowindow = new google.maps.InfoWindow({});
function initialize() {
var mapOptions = {
zoom: 2,
center: {
lat: 37.275,
lng: 22.549
},
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Create a <script> tag and set the USGS URL as the source.
var script = document.createElement('script');
script.src = 'https://pastebin.com/raw.php?i=7X956uB3';
document.getElementsByTagName('head')[0].appendChild(script);
map.data.setStyle(function(feature) {
var jstores = feature.getProperty('jstores');
return {
icon: getCircle(jstores),
title: (jstores)
};
});
}
function getCircle(jstores) {
var circle = {
path: google.maps.SymbolPath.CIRCLE,
fillColor: 'red',
fillOpacity: 0.2,
scale: Math.sqrt(jstores) * 2,
strokeColor: 'white',
strokeWeight: 0.5
};
return circle;
}
function jewellery_stores(results) {
map.data.addGeoJson(results);
map.data.addListener('click', function(e) {
infowindow.setPosition(e.latLng);
infowindow.setContent("hello world<br>jstores=" + e.feature.getProperty("jstores") + "<br>" + e.latLng.toUrlValue(6));
infowindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas"></div>

Categories

Resources