Google maps : Finding polygon by Id - javascript

Hi I have a polygon below :
var polygon = new google.maps.Polygon({
paths: coords,
id : 123,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: '#FF0000',
fillOpacity: 0.35
});
polygon.setMap(globalMap);
I attached an id property to it so i can refer to it later on, the problem is. How do I find that same polygon and trigger an event? like a change color or something?
function changePolygonColor(){
//refer to the polygon with id 123 (this is my question)
//change its color
polygon.fillColor = '#00FF00';
}
Many thanks!

From what I understand, you want to trigger an event after finding the polygon with a specific id.
Now, one thing you can do is just add an event listener to the polygon and refer to the polygon using the this context. You can then trigger the change of colour accordingly (for example):
google.maps.event.addListener(polygon, 'click', function (event) {
alert(this.id);
//Once you have the id here, you can trigger the color change
});
In your case however, if you don't want to trigger the color change on a specific even listener that can be added to the polygon. You could simply store the polygons in a polygon array and loop through them in your specific function that changes the colors. So you could try something like this (untested):
var polygonArray = []; //Have a global array of polygon elements
polygonArray.push(polygon); //Push your polygons as you create them into this polygon array
...
function changePolygonColor(){
//refer to the polygon with id 123 (this is my question)
//Loop through the polygon array
for (var i = 0; i < polygonArray.length; i++) {
if(polygonArray[i].id == 123) //Or whatever that you require
{
//change its color
polygon[i].fillColor = '#00FF00';
}
}
}
You might also want to check some other SO Posts on a similar issue. Hope this gets you started in the right direction.

Related

Leafletjs dynamically bound to visible markers/clusters

This is related to a previous question: Leafletjs dynamically bound map to visible overlays.
I am now using the Leaflet.FeatureGroup.SubGroup plugin with the Leaflet.markercluster plugin. Trying to set map bound to all visible markers and marker clusters. I am using 3 co-ordinates to test:
[43.6425657, -79.38705569999999]
[43.7164673, -79.3395846]
[-41.3142772, 174.8135975]
This is the code so far:
var map = L.map("mapid");
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(map);
map.setView([43.6532, -79.3832], 2);
var parentGroup = L.markerClusterGroup().addTo(map),
consultingMarkers = L.featureGroup.subGroup(parentGroup).addTo(map),
otherMarkers = L.featureGroup.subGroup(parentGroup).addTo(map);
// subGroup1
L.marker([43.6425657, -79.38705569999999]).addTo(consultingMarkers);
L.marker([43.7164673, -79.3395846]).addTo(consultingMarkers);
// subGroup2
L.marker([-41.3142772, 174.8135975], {icon: otherIcon}).addTo(otherMarkers);
var overlays = {
'consulting': consultingMarkers,
'other': otherMarkers
};
L.control.layers(null, overlays, {
collapsed: false
}).addTo(map);
map.on('overlayadd overlayremove', function () {
var bounds = parentGroup.getBounds(),
southWest = bounds.getSouthWest();
// Fit bounds only if the Parent Group actually has some markers,
// i.e. it returns valid bounds.
if (southWest && !southWest.equals(bounds.getNorthEast())) {
map.fitBounds(parentGroup.getBounds());
}
});
So far, I am running into these problems:
Map does not bound to the [-41.3142772, 174.8135975] co-ordinate
Un-checking the "consulting" layer does not bound the map to the markers from the "other" layer which has the co-ordinate [-41.3142772, 174.8135975].
Update: it seems to have this bounding problem for single markers. I tried adding another marker co-ordinate [43.76089289999999, -79.4103427] which would be in the cluster. But if I remove "consulting" cluster and remove "other" layer. The map still does not bound to the last marker left on the map.
If I understand correctly, you are puzzled because when one of your SubGroups has only 1 marker, the map.fitBounds does not look to be executed?
In that case, that is simply the expected behaviour of the !southWest.equals(bounds.getNorthEast()) check: it avoids executing the next block when bounds represents a null area, i.e. there is 0 or 1 marker into it.
By replacing the check by bounds.isValid(), you avoid only the case when there is 0 marker, but in the case there is exactly 1 marker, it will allow executing the next block, therefore trying to fit bounds on a null area. In such case, Leaflet pans to that single marker and zooms to maxZoom.
map.on('overlayadd overlayremove', function () {
var bounds = parentGroup.getBounds();
if (bounds.isValid()) {
map.fitBounds(bounds);
}
});
Demo: https://jsfiddle.net/3v7hd2vx/355/

How to scale and change background of Google Map marker with javascript

Is it possible to animate the scaling of the marker icon instead of just changing it to another icon with javascript?
I'ved added multiple markers to my Google Map as so:
var houseIcon = {
path: 'M0,12h4.5V7.5h3V12H12V6L6,0L0,6V12z',
fillColor: '#ff4b3d',
fillOpacity: 0.8,
scale: 1,
strokeColor: '#ff4b3d',
strokeWeight: 1
};
var marker = new google.maps.Marker({
position : latlng,
map : map,
id : 'post-'+marker_id,
icon: houseIcon
});
I wish to be able to scale the icon and preferrably also change it's backgroundcolor when I hover a html element located outside the Google Map.
I've used the setIcon() method to change the background ..but I'd like to, if possible, animate the scaling of the icon instead of just displaying a bigger icon.
Here is my current hover function:
$('.my-element').hover(
function() {
data_id = $(this).attr('data-id');
for( i= 0; i < map.markers.length; i++ ){
if( map.markers[i].id== 'post-'+data_id){
map.markers[i].setIcon("path-to-bigger-icon");
}
}
}, function() {
data_id = $(this).attr('data-id');
for( i= 0; i < map.markers.length; i++ ){
if( map.markers[i].id== 'post-'+data_id){
map.markers[i].setIcon("path-to-small-icon");
}
}
}
);
I solved this by using RichMarker and attaching my events to the content elements added to the marker.

Google Maps GeoComplete with GeoJson

I am struggling to get Google Maps to show me the data stored in a GeoJSON object. If I use a click event on the polygon it works first time. Code below:
// Get the GeoJSON file from the server
HTTP.get(Meteor.absoluteUrl("/geo.json"), function(err,result) {
GoogleMaps.maps.fibreMap.instance.data.loadGeoJson("/geo.json");
});
// Add style and colouring to the map
GoogleMaps.maps.fibreMap.instance.data.setStyle(function(feature) {
// Get the Fibrehood Status
var status = feature.getProperty('status');
// Add colour accoring to status
if (status == "live") {
opacity = 0.65;
} else if (status == "build") {
opacity = 0.4;
} else if (status == "register_i") {
opacity = 0.2;
}
// Return the correct styling
return ({
fillColor: '#ec008c',
strokeColor: '#ec008c',
strokeOpacity: 0.35,
strokeWeight: 0,
fillOpacity: opacity
});
});
GoogleMaps.maps.fibreMap.instance.data.addListener('click', function(event) {
var hood = event.feature.getProperty('name');
var status = event.feature.getProperty('status');
console.log(hood + " : " + status);
});
However, when trying to use GeoComplete to drop a pin on an address, it does not run. I know that this should be triggered with some sort of event, like a marker dropping on the map or a Dom Element changing, but I cannot figure it out.
Does anyone have any insight into how to trigger events from the DOM or dropping a marker onto the map? I am a bit of a noob and would really appreciate any help.
Thanks
Mike
Does anyone have any insight into how to trigger events from the DOM or dropping a marker onto the map?
Sure, there is. Google Maps JS API has a well-documented example of working with map events and map markers.
In this example a marker will drop on the map where you clicked using the 'click event'.
// This event listener calls addMarker() when the map is clicked.
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng, map);
});
// Add a marker at the center of the map.
addMarker(bangalore, map);
}
// Adds a marker to the map.
function addMarker(location, map) {
// Add the marker at the clicked location, and add the next-available label
// from the array of alphabetical characters.
var marker = new google.maps.Marker({
position: location,
label: labels[labelIndex++ % labels.length],
map: map
});
}
Full demo is here.
Here's a link to a sample for Listening to DOM Events:
https://developers.google.com/maps/documentation/javascript/examples/event-domListener

getting/setting unique id to a leafletjs circlemarker

I have a map with several markers on it. I construct these markers with this piece of code:
var markers = {},
lbl = 'unique';
markers[lbl] = L.circleMarker(ll,
{ radius: 8,
fillColor: '#ff0000',
color: '#00ff00',
weight: 0,
opacity: 1,
fillOpacity: 0.9,
className: 'svgMarker'
})
.bindLabel('This is '+lbl)
.addTo(markerLayer)
.addTo(map)
.on('click', clickHandler);;
Within the clickHandler I want to load some stuff depending on which marker I clicked. To distinguish them, I have a lbl (label)var which holds the unique alphanumeric ID of the marker.
function clickHandler(event){
//- zoom to the marker
map.setView(ev.latlng, 16);
//- Load the marker dependent stuff.
// how can I pass the unique label to this function?
}
Is there a way to pass the unique id with the mouse event or is there an other way to give a 'property' to the marker which I can read out in the clickHandler?
just add a property to your marker (just javascript stuff) ... you can get it back with context 'this' in the event handler
var marker = L.marker([48.8588589,2.3470599]);
marker.id = 'unique_id';
marker.addTo(map);
marker.on('click', clickHandler);
function clickHandler(event) {
console.log(this.id);
}

Google map: Add click listener to each polygon

I am working on a webapplication.
I have a google map, where I add polygons from an array. I loop through that array and add the polygons to the map. I also need to add an event listener to the polygon click and alert the position of the polygon
This is what I'm doing
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
//Loop on the polygonArray
for (var i = 0; i < polygonArray.length; i++) {
//Add the polygon
var p = new google.maps.Polygon({
paths: polygonArray[i],
strokeWeight: 0,
fillColor: '#FF0000',
fillOpacity: 0.6,
indexID: i
});
p.setMap(map);
//Add the click listener
google.maps.event.addListener(p, 'click', function (event) {
//alert the index of the polygon
alert(p.indexID);
});
}
Problem
The polygons are all drawing correctly. However the problem is that when I try to click on a polygon it always shows the last index. it is like it is only clicking on the last polygon added. I think when I add a new listener it overrides the old one. How can I add a listener for each polygon added in order to alert the correct index?
Thanks
It's the normal behavior.
There is two solutions that I can think of :
1) I am sure you can find back the polygon from the context (I didn't test it):
google.maps.event.addListener(polygon, 'click', function (event) {
alert(this.indexID);
});
2) You could also use some closures:
var addListenersOnPolygon = function(polygon) {
google.maps.event.addListener(polygon, 'click', function (event) {
alert(polygon.indexID);
});
}
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
//Loop on the polygonArray
for (var i = 0; i < polygonArray.length; i++) {
//Add the polygon
var p = new google.maps.Polygon({
paths: polygonArray[i],
strokeWeight: 0,
fillColor: '#FF0000',
fillOpacity: 0.6,
indexID: i
});
p.setMap(map);
addListenersOnPolygon(p);
}
Move the code block inside the for-loop.
//Add the click listener
google.maps.event.addListener(p, 'click', function (event) {
//alert the index of the polygon
alert(p.indexID);
});
OR
You add this to for-loop,
p.addListener('click', clickSelection);
and do this
function clickSelection(){
alert("Clicked");
}

Categories

Resources