Add infowindow and custom icon to Google map using Geojson - javascript

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>

Related

Google Maps forEach with setMap to set polyline visiblity (error: setMap is not a function)

I am trying to set the visibility of polylines based on a property. I use forEach to iterate over the features in the GeoJson data but when I try and call setMap on the array, I get type error: setMap is not a function. I have also tried pushing the resulting features into a new array with the same result.
map.data.loadGeoJson(
'data/trails2018.geojson', {},
function(features) {
console.log("loadGeoJson callback "+features.length);
map.data.forEach(function(feature) {
var skill = feature.getProperty('skill_leve');
if (skill == 'ADVANCED'){
feature.setMap(null);
}
});
});
You control the visibility of features on a Data Layer with the style property visible.
map.data.setStyle(function(feature) {
var visible = false;
if (feature.getProperty('skill_level')) {
var skill = feature.getProperty('skill_level');
if (skill == 'ADVANCED') {
visible = true;
}
}
return /** #type {google.maps.Data.StyleOptions} */ ({
strokeColor: "blue",
visible: visible
});
});
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(-23.55865, -46.65953),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var features = map.data.addGeoJson(geoJson);
console.log("addGeoJson returns " + features.length);
map.data.forEach(function(feature) {
var skill = feature.getProperty('skill_level');
if (skill == 'ADVANCED') {
// feature.setMap(null);
}
});
map.data.setStyle(function(feature) {
var visible = false;
if (feature.getProperty('skill_level')) {
var skill = feature.getProperty('skill_level');
if (skill == 'ADVANCED') {
visible = true;
}
}
return /** #type {google.maps.Data.StyleOptions} */ ({
strokeColor: "blue",
visible: visible
});
});
}
google.maps.event.addDomListener(window, "load", initialize);
var geoJson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"id": 1,
"skill_level": "ADVANCED"
},
"geometry": {
"type": "LineString",
"coordinates": [
[-43.48283, -23.02487],
[-43.65903, -23.55888]
]
}
},
{
"type": "Feature",
"properties": {
"id": 2,
"skill_level": "BEGINNER"
},
"geometry": {
"type": "LineString",
"coordinates": [
[-46.65953, -23.02487],
[-46.65903, -23.55888]
]
}
}
]
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

leaflet map, getting specific data of geojson file with button

I'm triying to display on my map specific value ( data.geojson) of my geojson file with buttons. (for exemple to plot a map with only value "domaine":"violences ")
I am loocking for a way to rely my data ("domaine":"violences" or other)with a buttons on my map ?
Thanks so much in advance for your time.
my js:
<script type="text/javascript">
var map = L.map('map');
var terrainTiles = L.tileLayer('http://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.{ext}', {
attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
subdomains: 'abcd',
minZoom: 0,
maxZoom: 20,
ext: 'png'
});
terrainTiles.addTo(map);
map.setView([46.5160000, 6.6328200], 10);
L.control.locate(location).addTo(map);
function addDataToMap(data, map) {
var dataLayer = L.geoJson(data, {
onEachFeature: function(feature, layer) {
var popupText = "<b>" + feature.properties.nom
+ "<br>"
+ "<small>" + feature.properties.localite
+ "<br>Rue: " + feature.properties.rue + + feature.properties.num
+ "<br>Téléphone: " + feature.properties.tel
+ "<br><a href= '" + feature.properties.url + "'>Internet</a>";
layer.bindPopup(popupText); }
});
dataLayer.addTo(map);
}
$.getJSON("data.geojson", function(data) { addDataToMap(data, map); });
</script>
</body>
</html>
the data.geojson
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ 6.1200622,46.2106091 ]
},
"properties": {
"nom":"Centre d'entraînement aux méthodes d'éducation active - Genève",
"rue":"Route des Franchises",
"num":"11",
"npa":1203,
"localite":"Genève",
"canton":"GE",
"tel":"022 940 17 57",
"url":"www.formation-cemea.ch",
"domaine":"formation "
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ 6.1243056,46.2120426 ]
},
"properties": {
"nom":"VIRES",
"rue":"Rue Ernest-Pictet ",
"num":"10",
"npa":1203,
"localite":"Genève",
"canton":"GE",
"tel":"022 328 44 33",
"url":"www.vires.ch",
"domaine":"violences "
}
}
As for toggling ON / OFF your categories, you could use Leaflet Layers Control L.control.layers.
As for grouping your features by category ("domaine" in your case), see the post I linked in my comment: Leaflet: How to toggle GeoJSON feature properties from a single collection?
You could even slightly simplify it by directly using Layer Groups L.layerGroup instead of using intermediate arrays.
var categories = {},
category;
var layersControl = L.control.layers(null, null).addTo(map);
function addDataToMap(data, map) {
L.geoJson(data, {
onEachFeature: function(feature, layer) {
category = feature.properties.domaine;
// Initialize the category layer group if not already set.
if (typeof categories[category] === "undefined") {
categories[category] = L.layerGroup().addTo(map);
layersControl.addOverlay(categories[category], category);
}
categories[category].addLayer(layer);
}
});
//dataLayer.addTo(map); // no longer add the GeoJSON layer group to the map.
}
$.getJSON("data.geojson", function(data) {
addDataToMap(data, map);
});
Demo: https://plnkr.co/edit/H6E6q0vKwb3RPOZBWs27?p=preview

Leaflet markers on localstorage, how to get marker lat lng and exclude from storage?

I created a function that on click places a marker on map, and save it to localstorage. Inside the marker popup, its displayed the marker position, and a delete button.
How I can make that delete button get actual marker position, compare to the ones stored in localstorage, and if find an equal value, delete it from local storage?
Using this:
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
console.log( localStorage.getItem( localStorage.key( i ) ) );
}
I get the what's in localstorage, I noticed that the markers are saved with a "\", any way to improve this code?
["{\"lat\":1780,\"lng\":456}","{\"lat\":1280,\"lng\":904}","{\"lat\":1000,\"lng\":-132}","{\"lat\":216,\"lng\":300}"]
The code:
function onMapClick(e) {
var geojsonFeature = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [e.latlng.lat, e.latlng.lng]
}
}
var marker;
L.geoJson(geojsonFeature, {
pointToLayer: function(feature, latlng){
marker = L.marker(e.latlng, {
title: "Resource Location",
alt: "Resource Location",
riseOnHover: true,
draggable: false,
icon: totem
}).bindPopup("<span>X: " + e.latlng.lng + ", Y: " + e.latlng.lat + "</span><br><a href='#' id='marker-delete-button'>Delete marker</a>");
marker.on("popupopen", onPopupOpen);
marker.on("dragend", function (ev) {
var chagedPos = ev.target.getLatLng();
this.bindPopup(chagedPos.toString()).openPopup();
});
// Begin store markers in local storage
storeMarker(e.latlng);
// End store markers in local storage
return marker;
}
}).addTo(map);
}
function onPopupOpen() {
var tempMarker = this;
$("#marker-delete-button:visible").click(function () {
map.removeLayer(tempMarker);
localStorage.removeItem("markers");
});
}
/// Load markers
function loadMarkers(){
var markers = localStorage.getItem("markers");
if(!markers) return;
markers = JSON.parse(markers);
markers.forEach(function(entry) {
latlng = JSON.parse(entry);
var geojsonFeature = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [latlng.lat, latlng.lng]
}
}
var marker;
L.geoJson(geojsonFeature, {
pointToLayer: function(feature){
marker = L.marker(latlng, {
title: "Resource Location",
alt: "Resource Location",
riseOnHover: true,
draggable: true,
icon: totem
}).bindPopup("<span>X: " + latlng.lng + ", Y: " + latlng.lat + "</span><br><a href='#' id='marker-delete-button'>Delete marker</a>");
marker.on("popupopen", onPopupOpen);
return marker;
}
}).addTo(map);
});
}
/// Store markers
function storeMarker(marker){
var markers = localStorage.getItem("markers");
if(!markers) {
markers = new Array();
console.log(marker);
markers.push(JSON.stringify(marker));
}
else
{
markers = JSON.parse(markers);
markers.push(JSON.stringify(marker));
}
console.log(JSON.stringify(markers));
localStorage.setItem('markers', JSON.stringify(markers));
}
map.on('click', onMapClick);
loadMarkers();
You seem to be confused about what locaStorage is/does, it stores data as key:value pairs, so what you have there is basically a list of stuff where you have:
key: \"lat\":1780,
value: \"lng\":456
As for deleting geoJSON features, a possibility is to use is the function onEachFeature() that can bind a function to geoJSON features before they are added to the map, so perhaps you can use that to bind a delete function when the delete button of the popup is clicked but while it can remove the layer from the map, it will not wipe the data from localStorage as leaflet as no way of referencing the data there.
Another possibility is to add unique id's to your points when creating them so you can reference them more easily when you want to remove them from database.

Overlapping Pointers with MarkerClustererPlus and OverlappingMarkerSpiderfier

I have this map and displaying pointers based on users long and lat. now i have a problem with OverlappingMarkerSpiderfier. when there are more than 1 users with same long and lat. for example: 5 people live in the same building. i need OverlappingMarkerSpiderfier to show the count and then on click to sipderfy it. by default, OverlappingMarkerSpiderfier doesnt work that way.
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52, 8),
zoom: 4
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var oms = new OverlappingMarkerSpiderfier(map,{markersWontMove: true, markersWontHide: true, keepSpiderfied: true});
markerClusterer.setMap(map);
here is the jsfiddle http://jsfiddle.net/gL3L7zso/62/
as you can see, when i click the battefield 3. its showing 1 pointer behind it hiding 3. i need it to be the same but, display the count of pointers hiding behind.
appreciate any solution for this.
update: to make the question more clear.
updated fiddle: http://jsfiddle.net/gL3L7zso/68
One option would be to put a label on each marker in the "cluster", and put the highest labeled marker on top.
oms.addMarker(marker);
var markersNear = oms.markersNearMarker(marker, false);
marker.setLabel("" + (markersNear.length + 1));
marker.setOptions({
zIndex: markersNear.length
});
proof of concept fiddle
code snippet:
var geoJson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"name": "Bielefeld"
},
"geometry": {
"type": "Point",
"coordinates": [8.528849, 52.030656]
}
}, {
"type": "Feature",
"properties": {
"name": "Bielefeld2"
},
"geometry": {
"type": "Point",
"coordinates": [8.528849, 52.030656]
}
}, {
"type": "Feature",
"properties": {
"name": "Bielefeld3"
},
"geometry": {
"type": "Point",
"coordinates": [8.528849, 52.030656]
}
}, {
"type": "Feature",
"properties": {
"name": "Herford"
},
"geometry": {
"type": "Point",
"coordinates": [8.676780, 52.118003]
}
}, {
"type": "Feature",
"properties": {
"name": "Guetersloh"
},
"geometry": {
"type": "Point",
"coordinates": [8.383353, 51.902917]
}
}, {
"type": "Feature",
"properties": {
"name": "Guetersloh2"
},
"geometry": {
"type": "Point",
"coordinates": [8.38, 51.9]
}
}]
};
var map = null;
var bounds = new google.maps.LatLngBounds();
var boxText = document.createElement("div");
boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
var infobox = new InfoBox({
content: boxText,
disableAutoPan: false,
maxWidth: 0,
pixelOffset: new google.maps.Size(-140, 0),
zIndex: null,
boxStyle: {
background: "url('tipbox.gif') no-repeat",
opacity: 0.75,
width: "280px"
},
closeBoxMargin: "10px 2px 2px 2px",
closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
infoBoxClearance: new google.maps.Size(1, 1),
isHidden: false,
pane: "floatPane",
enableEventPropagation: false
});
var markerClusterer = new MarkerClusterer(map, [], {imagePath: "https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m"});
minClusterZoom = 14;
markerClusterer.setMaxZoom(minClusterZoom);
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.030656,8.528849),
zoom: 14
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function() {
var oms = new OverlappingMarkerSpiderfier(map, {
markersWontMove: true,
markersWontHide: true,
keepSpiderfied: true
});
oms.addListener('unspiderfy', function(spidered, unspidered) {
for (var i = 0; i < spidered.length; i++) {
spidered[i].setLabel("" + (i + 1));
spidered[i].setOptions({
zIndex: i
});
}
});
markerClusterer.setMap(map);
google.maps.event.addListener(map.data, 'addfeature', function(e) {
if (e.feature.getGeometry().getType() === 'Point') {
var marker = new google.maps.Marker({
position: e.feature.getGeometry().get(),
title: e.feature.getProperty('name'),
map: map
});
google.maps.event.addListener(marker, 'click', function(marker, e) {
return function() {
var myHTML = e.feature.getProperty('name');
boxText.innerHTML = "<div style='text-align: center;'><b>" + myHTML + "</b></div>";
infobox.setPosition(e.feature.getGeometry().get());
infobox.setOptions({
pixelOffset: new google.maps.Size(0, 0)
});
infobox.open(map);
};
}(marker, e));
markerClusterer.addMarker(marker);
oms.addMarker(marker);
google.maps.event.addListener(map, 'idle', function() {
var markersNear = oms.markersNearMarker(marker, false);
marker.setLabel("" + (markersNear.length + 1));
marker.setOptions({
zIndex: markersNear.length
});
});
}
});
layer = map.data.addGeoJson(geoJson);
map.data.setMap(null);
google.maps.event.addListener(map, "click", function() {
infobox.close();
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
width: 100%;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
<script src="https://jawj.github.io/OverlappingMarkerSpiderfier/bin/oms.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/google-maps-utility-library-v3-infobox#1.1.14/dist/infobox.min.js"></script>
<div id="map"></div>

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>

Categories

Resources