Google Maps GeoJSON feature trigger click event - javascript

I have a featurecollection of features with their corresponding IDs like this:
"type"=>"Feature",
"id"=>"test_1",
"properties"=>array("desc"=>...
and want to trigger a click event from a button on the document so that the infowindow opens.
var featId = 'test_1';
map.event.trigger(featId, 'click');
but I'm getting
Uncaught TypeError: Cannot read property 'trigger' of undefined
The infowindow opens when I click on the polygon on the map.
Here's a JS fiddle.
I've also added a code snippet using stackoverflow's editor.
var mygeojson={
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
'id':'test_2',
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
0.5767822265625,
46.437856895024204
],
[
0.560302734375,
46.160809861457125
],
[
0.9118652343749999,
46.10370875598026
],
[
1.42822265625,
46.22545288226939
],
[
0.9118652343749999,
46.581518465658014
],
[
0.5767822265625,
46.437856895024204
]
]
]
}
},
{
"type": "Feature",
'id':'test_1',
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
1.9335937499999998,
46.98774725646568
],
[
1.8841552734374998,
46.73233101286786
],
[
2.581787109375,
46.53619267489863
],
[
2.8784179687499996,
46.71350244599995
],
[
3.065185546875,
47.00647991252098
],
[
2.3785400390625,
47.18597932702905
],
[
2.1917724609375,
47.60986653003798
],
[
1.9335937499999998,
46.98774725646568
]
]
]
}
}
]
};
function openinfo(target_featId)
{
//map.event.trigger(featId, 'click');
google.maps.event.trigger(map, 'click');
}
initpage = function()
{
var selected_id = 0;
console.log('html loaded');
//center lat/lon
var latlng = new google.maps.LatLng(46.315,0.467);
//map configutations
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: true,
};
map = new google.maps.Map(document.getElementById("themap"), myOptions);
map.data.addGeoJson(mygeojson);
map.data.setStyle(function(feature) {
//var SD_NAME = feature.getProperty('SD_NAME');
//var color = feature.getProperty('boja');
var featId = feature.getId();
var color = 'gray';
if(selected_id == featId)
{
color='#009900';
console.log('setting green for '+featId)
} else
{
color = 'gray';
console.log('setting gray for '+featId)
}
return {
fillColor: color,
strokeColor: color,
strokeWeight: 1
}
});
var infowindow = new google.maps.InfoWindow();
map.data.addListener('click', function(event) {
//var feat_desc = event.feature.getProperty("desc");
var featId = event.feature.getId();
map.data.forEach(function(feature2) {
if(featId == selected_id) feature2.setProperty('color','gray');
});
selected_id = featId;
var color = '#009900';
infowindow.setContent("<div style='width:150px; color: #000;'> litttle test "+featId+"</div>");
// position the infowindow on the marker
infowindow.setPosition(event.feature.getGeometry().getAt(0).getAt(0));
infowindow.open(map);
});
}
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px; background: #fff; color: #bbb; font-size: 13px; font-family: Arial;}
#themap { height:100%; }
<html>
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js"></script>
</head>
<body onload="initpage()">
Open poly 1
Open poly 2<br /><br />
<div id="themap">
</div>
</body>
</html>

I've successfully fixed this by using:
function openinfo(target_featId)
{
google.maps.event.trigger(map.data,'click',target_featId);
}
and then had a new issue with the addListener function. the event.feature was undefined, so I fixed it with:if(!event.feature) event.feature=event; inside map.data.addListener('click', function(event) {

Related

Multiple Geojson source layer ordering problem in google maps

I tried to load multiple geojson file to my google maps and all of them are shown. But the way the google maps show them is really random.
Here is my concept:
I have a polygon which i intended making as a base layer that suppose to appear first.
I have other polygon and linestring which will dynamically change from database and suppose to show on top of the base layer.
Sometimes the base layer will appear on top and vice versa. And other times, some of the linestring appear at the bottom of the base layer while some others at the top. Is there any way to order how the geojson layer appear?
I found similar problem: KML Layers rendering order google maps
but, that is for kml not geojson.
var map;
var src = '<?php echo base_url() ?>assets/map_files/global/barudt.json';
function initMap() {
map = new google.maps.Map(document.getElementById('googlemapsBorders'), {
center: new google.maps.LatLng(-0.7, 115.2422315),
zoom: 9,
mapTypeId: 'roadmap'
});
var infoWindows = new google.maps.InfoWindow({
disableAutoPan: true
});
var infoJalan = new google.maps.InfoWindow();
map.data.loadGeoJson(src);
map.data.setStyle(function(feature) {
var color = feature.getProperty('color');
return /** #type {!google.maps.Data.StyleOptions} */ ({
fillColor: color,
strokeColor: color,
strokeWeight: 2
});
});
// When the user clicks, set 'isColorful', changing the color of the letters.
map.data.addListener('click', function(event) {
event.feature.setProperty('isColorful', true);
});
map.data.addListener('mouseover', function(event) {
map.data.revertStyle();
map.data.overrideStyle(event.feature, {
strokeWeight: 5
});
var title = event.feature.getProperty('Name');
var lt = parseFloat(event.feature.getProperty('lat'));
var lg = parseFloat(event.feature.getProperty('lng'));
infoWindows.setContent(title);
infoWindows.setPosition({
lat: lt,
lng: lg
});
infoWindows.open(map);
});
map.data.addListener('mouseout', function(event) {
map.data.revertStyle();
infoWindows.close();
});
var jalan = JSON.parse(`<?php echo $detail; ?>`);
var jembatan = JSON.parse(`<?php echo $jembatan_detail; ?>`);
var infoWindow = new google.maps.InfoWindow(),
marker, i;
var infoWindowContent = JSON.parse(`<?php echo ($infowindow); ?>`);
console.log(jalan);
console.log(jembatan);
console.log(infoWindowContent);
jalanLayer = new google.maps.Data({
map: map,
style: {
strokeColor: 'red',
strokeWeight: 5
}
});
for (i = 0; i < jalan.length; i++) {
jalanLayer[i] = new google.maps.Data({
map: map,
style: {
strokeColor: 'red',
strokeWeight: 3,
fillColor: 'blue'
}
});
jalanLayer[i].loadGeoJson('<?php echo base_url('
assets / map_files / ') ?>' + jalan[i][1]);
var lt;
var lg;
jalanLayer[i].addListener('click', function(event) {
//alert("Latitude: " + event.latLng.lat() + " " + ", longitude: " + event.latLng.lng());
lt = parseFloat(event.latLng.lat());
lg = parseFloat(event.latLng.lng());
console.log(event.latLng.lat() + ',' + event.latLng.lng());
});
google.maps.event.addListener(jalanLayer[i], 'click', (function(nama, i) {
return function() {
var title;
jalanLayer[i].forEach(function(feature) {
title = "<div id=content>\n\
<div id=bodyContent>\n\
<table><tr><td>Nama Ruas Jalan</td><td>:</td><td><b>" + jalan[i][2] + "</b></td></tr><tr><td>Status Ruas Jalan</td><td>:</td><td><b>" + jalan[i][4] + "</b></td></tr><tr><td>Fungsi Ruas Jalan</td><td>:</td><td><b>" + jalan[i][3] + "</b></td></tr></table></div></div>";
});
infoJalan.setContent(title);
infoJalan.setPosition({
lat: lt,
lng: lg
});
infoJalan.open(map);
map.setZoom(14);
map.setCenter(infoJalan.getPosition());
};
})(jalanLayer[i], i));
google.maps.event.addListener(jalanLayer[i], 'mouseover', (function(nama, i) {
return function() {
jalanLayer[i].setStyle({
strokeColor: 'yellow'
});
};
})(jalanLayer[i], i));
google.maps.event.addListener(jalanLayer[i], 'mouseout', (function(nama, i) {
return function() {
jalanLayer[i].setStyle({
strokeColor: 'red'
});
};
})(jalanLayer[i], i));
}
for (i = 0; i < jembatan.length; i++) {
if (jembatan[i][4]) {
var icon = {
url: 'https://dispupr.baritoutarakab.go.id/assets/map_icon/jembatan.png',
scaledSize: new google.maps.Size(40, 40)
};
var position = new google.maps.LatLng(jembatan[i][2], jembatan[i][3]);
marker = new google.maps.Marker({
position: position,
map: map,
icon: icon,
title: jembatan[i][1]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
};
})(marker, i));
}
}
var area = new google.maps.Data({
map: map
});
area.loadGeoJson('<?php echo base_url() ?>assets/map_files/area/danau_butong.geojson');
area.setStyle({
fillColor: 'blue',
strokeColor: 'blue',
strokeWeight: 2
});
area.addListener('click', function(event) {
lt = parseFloat(event.latLng.lat());
lg = parseFloat(event.latLng.lng());
console.log(event.latLng.lat() + ',' + event.latLng.lng());
});
}
The DataLayer supports setting the zIndex on the Polygons in the styling function.
You didn't provide your GeoJSON, but using Google's example data, you could do something like this:
map.data.setStyle(function(feature) {
var color = 'gray';
var letter = feature.getProperty('letter')
var zIndex = 0;
if (letter) {
zIndex = 1;
if (feature.getProperty('isColorful')) {
color = feature.getProperty('color');
}
}
return /** #type {!google.maps.Data.StyleOptions} */({
fillColor: color,
strokeColor: color,
strokeWeight: 2,
zIndex: zIndex
});
});
proof of concept fiddle
code snippet:
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: -28,
lng: 137
}
});
map.addListener('click', function(evt) {
console.log(evt.latLng.toUrlValue(6));
})
// Load GeoJSON.
map.data.addGeoJson(googleJson);
map.data.addGeoJson(googleBigPolygonJson);
// Color each letter gray. Change the color when the isColorful property
// is set to true.
map.data.setStyle(function(feature) {
var color = 'gray';
var letter = feature.getProperty('letter')
var zIndex = 0;
if (letter) {
zIndex = 1;
if (feature.getProperty('isColorful')) {
color = feature.getProperty('color');
}
}
return /** #type {!google.maps.Data.StyleOptions} */ ({
fillColor: color,
strokeColor: color,
strokeWeight: 2,
zIndex: zIndex
});
});
// When the user clicks, set 'isColorful', changing the color of the letters.
map.data.addListener('click', function(event) {
event.feature.setProperty('isColorful', true);
});
// When the user hovers, tempt them to click by outlining the letters.
// Call revertStyle() to remove all overrides. This will use the style rules
// defined in the function passed to setStyle()
map.data.addListener('mouseover', function(event) {
map.data.revertStyle();
if (event.feature.getProperty('letter'))
map.data.overrideStyle(event.feature, {
strokeWeight: 8
});
});
map.data.addListener('mouseout', function(event) {
map.data.revertStyle();
});
}
var googleJson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"letter": "G",
"color": "blue",
"rank": "7",
"ascii": "71"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[123.61, -22.14],
[122.38, -21.73],
[121.06, -21.69],
[119.66, -22.22],
[119.00, -23.40],
[118.65, -24.76],
[118.43, -26.07],
[118.78, -27.56],
[119.22, -28.57],
[120.23, -29.49],
[121.77, -29.87],
[123.57, -29.64],
[124.45, -29.03],
[124.71, -27.95],
[124.80, -26.70],
[124.80, -25.60],
[123.61, -25.64],
[122.56, -25.64],
[121.72, -25.72],
[121.81, -26.62],
[121.86, -26.98],
[122.60, -26.90],
[123.57, -27.05],
[123.57, -27.68],
[123.35, -28.18],
[122.51, -28.38],
[121.77, -28.26],
[121.02, -27.91],
[120.49, -27.21],
[120.14, -26.50],
[120.10, -25.64],
[120.27, -24.52],
[120.67, -23.68],
[121.72, -23.32],
[122.43, -23.48],
[123.04, -24.04],
[124.54, -24.28],
[124.58, -23.20],
[123.61, -22.14]
]
]
}
},
{
"type": "Feature",
"properties": {
"letter": "o",
"color": "red",
"rank": "15",
"ascii": "111"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[128.84, -25.76],
[128.18, -25.60],
[127.96, -25.52],
[127.88, -25.52],
[127.70, -25.60],
[127.26, -25.79],
[126.60, -26.11],
[126.16, -26.78],
[126.12, -27.68],
[126.21, -28.42],
[126.69, -29.49],
[127.74, -29.80],
[128.80, -29.72],
[129.41, -29.03],
[129.72, -27.95],
[129.68, -27.21],
[129.33, -26.23],
[128.84, -25.76]
],
[
[128.45, -27.44],
[128.32, -26.94],
[127.70, -26.82],
[127.35, -27.05],
[127.17, -27.80],
[127.57, -28.22],
[128.10, -28.42],
[128.49, -27.80],
[128.45, -27.44]
]
]
}
},
{
"type": "Feature",
"properties": {
"letter": "o",
"color": "yellow",
"rank": "15",
"ascii": "111"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[131.87, -25.76],
[131.35, -26.07],
[130.95, -26.78],
[130.82, -27.64],
[130.86, -28.53],
[131.26, -29.22],
[131.92, -29.76],
[132.45, -29.87],
[133.06, -29.76],
[133.72, -29.34],
[134.07, -28.80],
[134.20, -27.91],
[134.07, -27.21],
[133.81, -26.31],
[133.37, -25.83],
[132.71, -25.64],
[131.87, -25.76]
],
[
[133.15, -27.17],
[132.71, -26.86],
[132.09, -26.90],
[131.74, -27.56],
[131.79, -28.26],
[132.36, -28.45],
[132.93, -28.34],
[133.15, -27.76],
[133.15, -27.17]
]
]
}
},
{
"type": "Feature",
"properties": {
"letter": "g",
"color": "blue",
"rank": "7",
"ascii": "103"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[138.12, -25.04],
[136.84, -25.16],
[135.96, -25.36],
[135.26, -25.99],
[135, -26.90],
[135.04, -27.91],
[135.26, -28.88],
[136.05, -29.45],
[137.02, -29.49],
[137.81, -29.49],
[137.94, -29.99],
[137.90, -31.20],
[137.85, -32.24],
[136.88, -32.69],
[136.45, -32.36],
[136.27, -31.80],
[134.95, -31.84],
[135.17, -32.99],
[135.52, -33.43],
[136.14, -33.76],
[137.06, -33.83],
[138.12, -33.65],
[138.86, -33.21],
[139.30, -32.28],
[139.30, -31.24],
[139.30, -30.14],
[139.21, -28.96],
[139.17, -28.22],
[139.08, -27.41],
[139.08, -26.47],
[138.99, -25.40],
[138.73, -25.00],
[138.12, -25.04]
],
[
[137.50, -26.54],
[136.97, -26.47],
[136.49, -26.58],
[136.31, -27.13],
[136.31, -27.72],
[136.58, -27.99],
[137.50, -28.03],
[137.68, -27.68],
[137.59, -26.78],
[137.50, -26.54]
]
]
}
},
{
"type": "Feature",
"properties": {
"letter": "l",
"color": "green",
"rank": "12",
"ascii": "108"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[140.14, -21.04],
[140.31, -29.42],
[141.67, -29.49],
[141.59, -20.92],
[140.14, -21.04]
]
]
}
},
{
"type": "Feature",
"properties": {
"letter": "e",
"color": "red",
"rank": "5",
"ascii": "101"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[144.14, -27.41],
[145.67, -27.52],
[146.86, -27.09],
[146.82, -25.64],
[146.25, -25.04],
[145.45, -24.68],
[144.66, -24.60],
[144.09, -24.76],
[143.43, -25.08],
[142.99, -25.40],
[142.64, -26.03],
[142.64, -27.05],
[142.64, -28.26],
[143.30, -29.11],
[144.18, -29.57],
[145.41, -29.64],
[146.46, -29.19],
[146.64, -28.72],
[146.82, -28.14],
[144.84, -28.42],
[144.31, -28.26],
[144.14, -27.41]
],
[
[144.18, -26.39],
[144.53, -26.58],
[145.19, -26.62],
[145.72, -26.35],
[145.81, -25.91],
[145.41, -25.68],
[144.97, -25.68],
[144.49, -25.64],
[144, -25.99],
[144.18, -26.39]
]
]
}
}
]
}
var googleBigPolygonJson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[115.950195, -19.358593],
[151.80957, -19.68994],
[155.413086, -28.73469],
[148.645508, -36.426384],
[116.477539, -36.849535],
[113.665039, -24.252746],
[115.950195, -19.358593]
]
]
}
}]
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Data layer not responding in event listener (Google Maps API)

I have a function where I load a geoJSON into a map, then replace it when I hit specific zoom levels. The following works when the window.map.data.setMap(null); is commented out, but only to pile on all maps as the zoom level changes. Uncommenting out the setMap(null) lines removes the map once the zoom level changes, but does not allow a new file to replace it; I'm consistently getting undefined when binding the data layer to a variable (see image at end):
if($('#map').length) {
var styledMapType = new google.maps.StyledMapType(
//this is all styling
}
], {name: 'Styled Map'});
var toronto = {lat: 43.687508, lng: -79.304293};
if ($('#map').length) {
window.map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: toronto,
disableDefaultUI: false,
scrollwheel: false,
streetViewControl: false,
fullscreenControl: false,
mapTypeControl: false,
zoomControl: true,
});
zoom: 16,
center: listing_address,
disableDefaultUI: false,
scrollwheel: false,
streetViewControl: false,
fullscreenControl: false,
mapTypeControl: false,
});
.var county = {
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "AREA_NAME": "Toronto Region", "Name": "", "Description": "" }, "geometry": { "type": "Polygon", "coordinates": [ [
[ -79.331290752373903, 43.6257878530946 ],
[ -79.331317617252296, 43.6256985447421 ],
[ -79.331512561913399, 43.625640321883701 ],
[ -79.331752709965201, 43.625618170498399 ],
[ -79.331959376709506, 43.625519457784897 ],
[ -79.332109811020601, 43.625312645786401 ],
[ -79.333209007789605, 43.644149630451302 ],
[ -79.333365435394498, 43.644032839820198 ],
[ -79.431165436417103, 43.630306805590003 ],
[ -79.431488362803094, 43.630361005759099 ],
[ -79.431821347539696, 43.630419711640798 ],
[ -79.432139201596499, 43.630500911132103 ],
[ -79.432442343991099, 43.630573099758003 ],
[ -79.475947295799898, 43.623398134852998 ],
[ -79.280866209706105, 43.671017401276799 ],
[ -79.307699740463903, 43.656122040811901 ],
[ -79.307771442967393, 43.655987140776503 ],
[ -79.331356425413802, 43.625806618446397 ],
[ -79.331290752373903, 43.6257878530946 ] ] ] } }
]
}
var district = {
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "AREA_ID": "108", "CITY_NAME": "", "CITY_NAME": "", "AREA_NAME": "Briar Hill-Belgravia" }, "geometry": { "type": "Polygon", "coordinates": [ [
[ -79.464620647999908, 43.692155605999957 ],
[ -79.46522206099992, 43.693230269999958 ],
[ -79.465251297999913, 43.693298486999957 ],
[ -79.465279791999919, 43.693366811999958 ],
[ -79.46530741699992, 43.693435416999954 ],
[ -79.465719907999926, 43.694757514999957 ],
[ -79.44101562199991, 43.705410816999958 ],
[ -79.440110285999921, 43.705585372999955 ],
[ -79.447685296999921, 43.696258794999956 ],
[ -79.449336555999921, 43.695897948999956 ],
[ -79.450278980999911, 43.695691998999955 ],
[ -79.451201995999909, 43.695476191999958 ],
[ -79.462902461999917, 43.69287652099996 ],
[ -79.463998089999919, 43.692404465999957 ],
[ -79.464620647999908, 43.692155605999957 ] ] ] } }
]
}
var cities ={
"type":"FeatureCollection", "features": [
{"type":"Feature","properties":
{"AREA_ID":49884,"AREA_NAME":"YORK","OBJECTID":11093905},"geometry":{"type":"Polygon","coordinates":[[[-79.49262446,43.64744493],
[-79.49249144,43.64772528],
[-79.49149894,43.65163426],
[-79.50094749,43.65228262],
[-79.503085,43.66113086],
[-79.5123581,43.67258877],
[-79.5126394,43.68922995],
[-79.50556991,43.70925399],
[-79.42776901,43.70053559],
[-79.42848543,43.68173363],
[-79.42909608,43.68160367],
[-79.48394351,43.66992188],
[-79.48405475,43.66989696],
[-79.48367372999999,43.66897745],
[-79.49262446,43.64744493]]]}},
]
}
window.map.mapTypes.set('styled_map', styledMapType);
window.map.setMapTypeId('styled_map');
// issue in question below:
if ($('#map').length) {
window.map.data.loadGeoJson( cities );
window.map.addListener('zoom_changed', function() {
var zoomLevel = map.getZoom();
if (zoomLevel <= 12 && zoomLevel >= 9) {
window.map.data.addGeoJson( cities );
} else if (zoomLevel < 9) {
window.map.data.addGeoJson( county );
} else if (zoomLevel > 12) {
window.map.data.addGeoJson( district );
};
})
window.map.data.setStyle({
fillOpacity: 0.2,
strokeWeight: 1,
strokeColor: '#1e1d1d',
fillColor: '#1e1d1d'
});
window.map.data.addListener('mouseover', function(event) {
window.map.data.overrideStyle(event.feature, {
strokeColor: '#0076c0',
fillColor: '#0076c0',
strokeWeight: 2.5,
});
});
window.map.data.addListener('mouseout', function(event) {
window.map.data.revertStyle();
});
window.map.data.addListener('click', function(event) {
window.map.data.overrideStyle(event.feature, {
strokeColor: '#0076c0',
fillColor: '#0076c0',
fillOpacity: 0.2
});
});
};
};
});
I tried the following already as per How to remove data from gmap? . Adding those variables wither above the first line of my code, or as the first section of the function before the if statement gave me unexpected identifier problems (I removed the actual code, this was my reference):
// load data - do the same for data2, data3 or whatever
data1 = new google.maps.Data();
data1.loadGeoJson(url1);
// create some layer control logic for turning on data1
data1.setMap(map) // or restyle or whatever
// turn off data1 and turn on data2
data1.setMap(null) // hides it
data2.setMap(map) // displays data2
And this is the result I'm currently getting when I set breakpoints:
What is the linkage I'm missing? The docs (https://developers.google.com/maps/documentation/javascript/reference/3.exp/#Data) suggest that loadGeoJSON and zoomchange aren't compatible methods, which seems really unlikely.
Seems to me what you want to do is create a DataLayer for each of the data sets. Then manage those based on the zoom level. Create them when they are first visible, set their map property to null when they are hidden, to your map variable when you want them visible.
var districtLayer, cityLayer, countyLayer;
window.map.addListener('zoom_changed', function() {
var zoomLevel = map.getZoom();
if (zoomLevel < 12 && zoomLevel > 9) {
// city level, hide district and county layers
if (districtLayer && districtLayer.setMap)
districtLayer.setMap(null);
if (countyLayer && countyLayer.setMap)
countyLayer.setMap(null);
if (countyLayer && countyLayer.setMap)
countyLayer.setMap(null);
if (!cityLayer) {
cityLayer = new google.maps.Data();
cityLayer.addGeoJson(cities);
}
cityLayer.setMap(map);
} else if (zoomLevel <= 9) {
// county level, hide city and county layers
if (cityLayer && cityLayer.setMap)
cityLayer.setMap(null);
if (districtLayer && districtLayer.setMap)
districtLayer.setMap(null);
if (!countyLayer) {
countyLayer = new google.maps.Data();
countyLayer.addGeoJson(county);
}
countyLayer.setMap(map);
} else if (zoomLevel >= 12) {
// city level, hide district and county layers
if (cityLayer && cityLayer.setMap)
cityLayer.setMap(null);
if (countyLayer && countyLayer.setMap)
countyLayer.setMap(null);
if (!districtLayer) {
districtLayer = new google.maps.Data();
districtLayer.addGeoJson(district);
}
districtLayer.setMap(map);
}
});
proof of concept fiddle
code snippet:
function initialize() {
var districtLayer, cityLayer, countyLayer;
if ($('#map').length) {
var toronto = {
lat: 43.689577,
lng: -79.453715
};
window.map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: toronto,
disableDefaultUI: false,
scrollwheel: false,
streetViewControl: false,
fullscreenControl: false,
mapTypeControl: false,
});
window.map.addListener('zoom_changed', function() {
var zoomLevel = map.getZoom();
if (districtLayer && districtLayer.setMap)
districtLayer.setMap(null);
if (countyLayer && countyLayer.setMap)
countyLayer.setMap(null);
document.getElementById('zoom').innerHTML = zoomLevel;
if (zoomLevel < 12 && zoomLevel > 9) {
document.getElementById('zoom').innerHTML += ":city";
if (countyLayer && countyLayer.setMap)
countyLayer.setMap(null);
if (!cityLayer) {
cityLayer = new google.maps.Data();
cityLayer.addGeoJson(cities);
}
cityLayer.setMap(map);
} else if (zoomLevel <= 9) {
document.getElementById('zoom').innerHTML += ":county";
if (cityLayer && cityLayer.setMap)
cityLayer.setMap(null);
if (districtLayer && districtLayer.setMap)
districtLayer.setMap(null);
if (!countyLayer) {
countyLayer = new google.maps.Data();
countyLayer.addGeoJson(county);
}
countyLayer.setMap(map);
} else if (zoomLevel >= 12) {
document.getElementById('zoom').innerHTML += ":district";
if (cityLayer && cityLayer.setMap)
cityLayer.setMap(null);
if (countyLayer && countyLayer.setMap)
countyLayer.setMap(null);
if (!districtLayer) {
districtLayer = new google.maps.Data();
districtLayer.addGeoJson(district);
}
districtLayer.setMap(map);
}
});
google.maps.event.trigger(map, 'zoom_changed');
}
}
google.maps.event.addDomListener(window, "load", initialize);
var county = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"AREA_NAME": "Toronto Region",
"Name": "",
"Description": ""
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-79.486178, 43.59873],
[-79.514712, 43.719608],
[-79.260958, 43.755659],
[-79.230746, 43.634522],
[-79.486178, 43.59873]
]
]
}
}]
};
var district = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"AREA_ID": "108",
"CITY_NAME": "",
"CITY_NAME": "",
"AREA_NAME": "Briar Hill-Belgravia"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-79.464620647999908, 43.692155605999957],
[-79.46522206099992, 43.693230269999958],
[-79.465251297999913, 43.693298486999957],
[-79.465279791999919, 43.693366811999958],
[-79.46530741699992, 43.693435416999954],
[-79.465719907999926, 43.694757514999957],
[-79.44101562199991, 43.705410816999958],
[-79.440110285999921, 43.705585372999955],
[-79.447685296999921, 43.696258794999956],
[-79.449336555999921, 43.695897948999956],
[-79.450278980999911, 43.695691998999955],
[-79.451201995999909, 43.695476191999958],
[-79.462902461999917, 43.69287652099996],
[-79.463998089999919, 43.692404465999957],
[-79.464620647999908, 43.692155605999957]
]
]
}
}]
}
var cities = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties":
{
"AREA_ID": 49884,
"AREA_NAME": "YORK",
"OBJECTID": 11093905
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-79.49262446, 43.64744493],
[-79.49249144, 43.64772528],
[-79.49149894, 43.65163426],
[-79.50094749, 43.65228262],
[-79.503085, 43.66113086],
[-79.5123581, 43.67258877],
[-79.5126394, 43.68922995],
[-79.50556991, 43.70925399],
[-79.42776901, 43.70053559],
[-79.42848543, 43.68173363],
[-79.42909608, 43.68160367],
[-79.48394351, 43.66992188],
[-79.48405475, 43.66989696],
[-79.48367372999999, 43.66897745],
[-79.49262446, 43.64744493]
]
]
}
}, ]
};
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>
<div id="zoom"></div>
<div id="map"></div>

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>

Google Maps API: getFeatureById for feature collection not working

I try to change the style of a specific feature of a feature collection data overlay. This is a snippet of my json:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"properties": {
"name": "1 CBD - Bankenviertel",
"color": "transparent",
"isHovered": false,
"isActive": false
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
8.67279430349,
50.1143807311
],
[
8.67280054398,
50.1143975981
]
]
]
}
}
and this is the relevant snippet from my map.js
map.data.loadGeoJson('some.json');
console.log(map.data.getFeatureById(1));
And I am always getting "undefined" in the console.
What am I doing wrong here?
Thanks,
Robert
You need to call map.data.getFeatureById(1) inside the callback function (so it doesn't execute before the GeoJson has loaded).
from the documentation:
loadGeoJson(url:string, options?:Data.GeoJsonOptions, callback?:function(Array<Data.Feature>))
Return Value: None
Loads GeoJS
proof of concept fiddle
code snippet:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
zoom: 4,
center: {
lat: -28,
lng: 137
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// map.data.addGeoJson(geoJson);
map.data.loadGeoJson(
'https://api.myjson.com/bins/1teyu', {},
function(features) {
console.log(map.data.getFeatureById(1));
console.log(map.data.getFeatureById(1).getProperty("letter"));
});
}
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>

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>

Categories

Resources