Leaflet Layergroups in loop - javascript

Hi i have this code that from txt file create markers on image map. And i want to add layer control to hide or show different markers with L.control.layers now with this code it hide all markers. Is it possible to split markers by coordinates into groups ? Thanks
var stringData = $.ajax({
url: "a.txt",
async: false
}).responseText;
//Split values of string data
var stringArray = stringData.split("\n");
var arrayLength = stringArray.length ;
var layerGroup = L.layerGroup().addTo(map);
for(var i = 0; i < arrayLength; i++) {
var x = $.trim(stringArray[i].split(",")[0]);
var y = $.trim(stringArray[i].split(",")[1]);
var img2 = $.trim(stringArray[i].split(",")[2]);
var circle = L.circle([x,y], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.3,
radius: 2,
}).addTo(map);
circle.url = img2
circle.on('click', function(){
window.location = (this.url);
});
layerGroup.addLayer(circle);
}
var overlayMaps = {
"Normal": layerGroup,
"Elite": layerGroup,
"Ultimate": layerGroup
};
L.control.layers(null, overlayMaps).addTo(map);
a.txt
-146.4375, 183.0625, img/img1.png
-104.5, 182.75, img/img2.png,

Yes of course. Just create 3 layerGroups. In your loop, you have to add a condition to add your circles to either of them.
var layerGroup1 = L.layerGroup().addTo(map);
var layerGroup2 = L.layerGroup().addTo(map);
var layerGroup3 = L.layerGroup().addTo(map);
for(var i = 0; i < arrayLength; i++) {
var x = $.trim(stringArray[i].split(",")[0]);
var y = $.trim(stringArray[i].split(",")[1]);
var img2 = $.trim(stringArray[i].split(",")[2]);
var circle = L.circle([x,y], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.3,
radius: 2,
});
circle.url = img2
circle.on('click', function(){
window.location = (this.url);
});
switch(img2) {
case "img/img1.png":
circle.addTo(layerGroup1);
break;
case "img/img2.png":
circle.addTo(layerGroup2);
break;
case "img/img3.png":
circle.addTo(layerGroup3);
break;
default:
break;
}
}
var overlayMaps = {
"Normal": layerGroup1,
"Elite": layerGroup2,
"Ultimate": layerGroup3
};
Example: http://plnkr.co/edit/f8azOmaz1ITLZiKgfHWt?p=preview

something like this ?
var layerGroup1 = L.layerGroup().addTo(map);
var layerGroup2 = L.layerGroup().addTo(map);
var layerGroup3 = L.layerGroup().addTo(map);
for(var i = 0; i < arrayLength; i++) {
var x = $.trim(stringArray[i].split(",")[0]);
var y = $.trim(stringArray[i].split(",")[1]);
var img2 = $.trim(stringArray[i].split(",")[2]);
var circle = L.circle([x,y], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.3,
radius: 2,
}).addTo(map).addTo(layerGroup1);
circle.url = img2
circle.on('click', function(){
window.location = (this.url);
});
if((img2 === "img/img2.png")||(img2 === "img/img3.png")){
var circle2 = L.circle([x,y], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.3,
radius: 2,
}).addTo(map).addTo(layerGroup2);
}
}
var overlayMaps = {
"Normal": layerGroup1,
"Elite": layerGroup2,
"Ultimate": layerGroup3
};
L.control.layers(null, overlayMaps).addTo(map);

Related

Filter data from database in Leaflet [duplicate]

I want to filter my markers by name, using map.addLayer(nameOfTheMarker) and map.remvoeLayer(nameOfTheLayer) with a checkbox like this:
$('#markertoggle').change(function () {
if (!this.checked)
// ^
map.addLayer(nameOfTheMarker);
else
map.remvoeLayer(nameOfTheLayer;
});
I found a jsfiddle with an example of a filter, but I don't know how to apply it to my code:
var locations = [
['AB11 5HW','17','A',57.147701,-2.085442 ] ,
['AB11 8DG','3','B',57.129372,-2.090916 ]
];
var markersA = [];
var markersB = [];
//Loop through the initial array and add to two different arrays based on the specified variable
for(var i=0; i < locations.length; i++) {
switch (locations[i][2]) {
case 'A' :
markersA.push(L.marker([locations[i][3], locations[i][4]]));
break;
case 'B' :
markersB.push(L.marker([locations[i][3], locations[i][4]]));
break;
default :
break;
}
}
//add the groups of markers to layerGroups
var groupA = L.layerGroup(markersA);
var groupB = L.layerGroup(markersB);
//background tile set
var tileLayer = {'Gray' : L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png')
};
var map = L.map('map', {
center: new L.LatLng(57.0, -2),
zoom: 9,
layers: [tileLayer['Gray'], groupA, groupB] //change this to determine which ones start loaded on screen
});
//Control on the Top Left that handles the switching between A and B
var overlayMaps = {
"A": groupA,
"B": groupB
};
L.control.layers(tileLayer, overlayMaps, {position:'topleft'}).addTo(map);
http://jsfiddle.net/RogerHN/31v2afte/2/
The function that I use to pull the markers:
function showMarkersByName(name) {
for (var i = 0; i < markers.resources.length; i++) {
var resName = markers.resources[i].name;
if (resName == name) {
var resIcon = icons.resources[i].icon;
var resSize = icons.resources[i].size;
var resPname = icons.resources[i].pname;
var customIcon = L.icon({
iconUrl: resIcon,
iconSize: resSize, // size of the icon
iconAnchor: [resSize[0]/2, resSize[1]/2], // point of the icon which will correspond to marker's location
popupAnchor: [2, -resSize[1]/2] // point from which the popup should open relative to the iconAnchor
});
for (var j = 0; j < markers.resources[i].coords.length; j++) {
var x = markers.resources[i].coords[j].x;
var y = markers.resources[i].coords[j].y;
marker = L.marker([y, x], {icon: customIcon});
marker.addTo(map).bindPopup(resPname);
$(marker._icon).addClass(name)
}
}
}
My markers structure its very similar with the one in the example, I just don't know where in my function I need to insert the filter to filter the markers by name, adding then to a layer to later toggle them use the checkbox above.
My full code here: http://plnkr.co/edit/UwAelIuUYz4OkoOG7zFn?p=preview
Using the example above and the code iH8 mentioned I was able to create a checkbox to toggle markers filtering them by its name:
function initLayerGroups() {
for (var i = 0; i < markers.resources.length; i++) {
switch (markers.resources[i].name) {
case 'GreenMarker':
for (var j = 0; j < markers.resources[i].coords.length; j++) {
var x = markers.resources[i].coords[j].x;
var y = markers.resources[i].coords[j].y;
marker = L.marker([y, x], {
icon: getIcon(i)
}).bindPopup(getPopupContent(i));
markersGreen.push(marker);
}
break;
case 'BlueMarker':
for (var j = 0; j < markers.resources[i].coords.length; j++) {
var x = markers.resources[i].coords[j].x;
var y = markers.resources[i].coords[j].y;
marker = L.marker([y, x], {
icon: getIcon(i)
}).bindPopup(getPopupContent(i));
markersBlue.push(marker);
}
break;
case 'RedMarker':
for (var j = 0; j < markers.resources[i].coords.length; j++) {
var x = markers.resources[i].coords[j].x;
var y = markers.resources[i].coords[j].y;
marker = L.marker([y, x], {
icon: getIcon(i)
}).bindPopup(getPopupContent(i));
markersRed.push(marker);
}
break;
default:
break;
}
}
groupGreen = L.layerGroup(markersGreen);
groupBlue = L.layerGroup(markersBlue);
groupRed = L.layerGroup(markersRed);
}
The checkbox:
<input type="checkbox" id="greenmarkertoggle"/>
<label for="greenmarkertoggle">Green Marker</label>
And the javascript code to show or hide the layer:
$('#greenmarkertoggle').change(function() {
if (this.checked)
map.addLayer(groupGreen);
else
map.removeLayer(groupGreen);
});
And here's the full working example using the code above:
http://plnkr.co/edit/GuIVhtFdtMDbmZdME1bV?p=preview
Thanks to iH8 and the example above I was able to create that function and filter the markers by its name.

I wanna achieve a function in GEE with JS: mosaic() each year into one image from Sentinel-2 then ee.ImageCollection.fromImages but errors continued

function maskS2clouds(image) {
var qa = image.select('QA60');
// Bits 10 and 11 are clouds and cirrus, respectively.
var cloudBitMask = 1 << 10;
var cirrusBitMask = 1 << 11;
// Both flags should be set to zero, indicating clear conditions.
var mask = qa.bitwiseAnd(cloudBitMask).eq(0)
.and(qa.bitwiseAnd(cirrusBitMask).eq(0));
return image.updateMask(mask).divide(10000).set({ 'system:time_start': image.get('system:time_start') });//error with or without it
}
var start='2018-01-01'
var end='2018-12-31'
var rgbVis = {
min: 0.0,
max: 0.3,
bands: ['red', 'green', 'blue'],
}
Map.centerObject(table, 14);
// Map the function over one month of data and take the median.
// Load Sentinel-2 TOA reflectance data.
var S2_BANDS = ['QA60','B12','B11', 'B8','B4', 'B3', 'B2']
var S2_NAMES = ['QA60','swir2','swir1', 'nir', 'red', 'green', 'blue']
var adds2 = function(image){
var awei= image.expression(
'4*(green-SWIR1)-(0.25*NIR+2.75*SWIR2)',{
green:image.select('green'),
NIR:image.select('nir'),
SWIR1:image.select('swir1'),
SWIR2:image.select('swir2'),
}).float().rename('AWEI')
var wetness = image.expression(
'(Blue*0.2578)+(Green* 0.2305)+(Red*0.0883)+(NIR1* 0.1071)+(SWIR1*-0.7611)+(SWIR2*-0.5308)',
{
Red: image.select('red'),
NIR1: image.select('nir'),
Blue: image.select('blue'),
Green: image.select('green'),
SWIR1: image.select('swir1'),
SWIR2: image.select('swir2')
}).float().rename('TCWetness')
var nwi= image.expression(
'Blue-(NIR+SWIR1+SWIR2)/Blue+(NIR+SWIR1+SWIR2)',{
Blue: image.select('blue'),
NIR:image.select('nir'),
SWIR1:image.select('swir1'),
SWIR2:image.select('swir2'),
}).float().rename('NWI')
var ndvi = image.normalizedDifference(['nir','red']).rename('NDVI')
var mndwi = image.normalizedDifference(['green','swir1']).rename('MNDWI')
var ndwi = image.normalizedDifference(['green','nir']).rename('NDWI')
return image.addBands([awei,wetness,nwi,ndvi,mndwi,ndwi]);
}
var dataset = ee.ImageCollection('COPERNICUS/S2')
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 10))
.map(maskS2clouds)
.select(S2_BANDS,S2_NAMES)
.filterBounds(table)
// .filterDate(start,end )
// .map(adds2)
Map.addLayer(dataset.median(), rgbVis, 'RGB')
var mos=function(start,end){
var one=dataset.filterDate(start,end ).mosaic()
return(one)
}
var y2015=mos('2015-01-01','2015-12-31')
var y2016=mos('2016-01-01','2016-12-31')
var y2017=mos('2017-01-01','2017-12-31')
var y2018=mos('2018-01-01','2018-12-31')
var y2019=mos('2019-01-01','2019-12-31')
var y2020=mos('2020-01-01','2020-12-31')
var y2021=mos('2021-01-01','2021-12-31')
var images=ee.ImageCollection.fromImages([y2015,y2016,y2017,y2018,y2019,y2020,y2021])
var images=images.map(adds2)
print(images)
var NDWI=dataset.select("NDWI")//-0.0429
var MNDWI=dataset.select("MNDWI")//0.355
var TCWetness=dataset.select("TCWetness")//-224.229
var AWEI=dataset.select('AWEI')//-1284.206
var NDVI=dataset.select('NDVI')//0.074
var otsu = function(histogram) {
var counts = ee.Array(ee.Dictionary(histogram).get('histogram'));
var means = ee.Array(ee.Dictionary(histogram).get('bucketMeans'));
var size = means.length().get([0]);
var total = counts.reduce(ee.Reducer.sum(), [0]).get([0]);
var sum = means.multiply(counts).reduce(ee.Reducer.sum(), [0]).get([0]);
var mean = sum.divide(total);
var indices = ee.List.sequence(1, size);
var bss = indices.map(function(i) {
var aCounts = counts.slice(0, 0, i);
var aCount = aCounts.reduce(ee.Reducer.sum(), [0]).get([0]);
var aMeans = means.slice(0, 0, i);
var aMean = aMeans.multiply(aCounts)
.reduce(ee.Reducer.sum(), [0]).get([0])
.divide(aCount);
var bCount = total.subtract(aCount);
var bMean = sum.subtract(aCount.multiply(aMean)).divide(bCount);
return aCount.multiply(aMean.subtract(mean).pow(2)).add(
bCount.multiply(bMean.subtract(mean).pow(2)));
});
print(ui.Chart.array.values(ee.Array(bss), 0, means));
return means.sort(bss).get([-1]);
};
var ALOSDEM = ee.Image("JAXA/ALOS/AW3D30_V1_1")
var slope = ee.Terrain.slope(ALOSDEM.clip(table))
var imgs=images.select('MNDWI')//'AWEI','NDWI','NWI','TCWetness',
var chart = ui.Chart.image.series(imgs,table, ee.Reducer.mean(),100)
chart.style().set({
position: 'bottom-right',
width: '500px',
height: '300px'
});
Map.add(chart);
var label=ui.Label('Date:M-D-Y')
Map.add(label)
https://code.earthengine.google.com/6eed1d39dc4cf1f284214293fab6af01
My plan is to create a function that clicks on the chart some year it will layer a water mask I wrote. After the problem above, still there will be errors if I wrote .onClick(function( var equalDate=ee.Filter.equals('system:time_start',x). how can I replace it?

Detecting which polyline-grids a line crosses

Last year I built an extensive multi-tiered system to create a grid of qtr-mins. It works well.
My client would now like to pass in lines (two nodes of LatLng) and would like me to return which Qtr Mins it touches. FWIW, a QtrMin is a polygon that is 1/60/4 (1/4 minute) by 1/60/4.
Below is the stripped down script. I have an entry function where I will pass in the line nodes and I will write an external function to pass out the QtrMins touched.
Part of the problem is that I have drawn my Qtr Mins from polylines but that is how it is.
I will be leveraging the script via Delphi and making a function call to pass in the Lat/Lng pairs.
function getQtrMinTouched(oLat,oLng, fLat,fLng){
// Lost and confused here
}
and depending how the result is returned, I will make a call through a com object to pass the QtrMin to my program. Passing in arguments to functions and passing out results are already solved. Including that here would contribute little but would entail several modules to simply run.
My question is: using the grids I create below, is there a way to determine which of those grids are touched by a line (LatLng, LatLng)? A line may span multiple grids. A line will always be defined as two nodes (LatLng, LatLng).
<html>
<head>
<title>Find your Qtr minute locator
</title>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.24&libraries=geometry">
</script>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<div id="map-canvas" style="HEIGHT: 100%; WIDTH: 100%" onclick=""></div>
<div id="map"></div>
<script type="text/javascript">
var map;
var llOffset = 1/60/4;
var qtrNELatLngCode;
var qtrNorth;
var qtrEast;
var qtrSWLatLngCode;
var qtrSouth;
var qtrWest;
var latPolylines = [];
var lngPolylines = [];
var lngLabels = [];
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map-canvas"), {
center: new google.maps.LatLng(34.0, -84.0),
zoom: 16,
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true
});
google.maps.event.addListener(map, "idle", function () {
var sLat = map.getCenter().lat();
var sLng = map.getCenter().lng();
//external.ShowMarker(sLat,sLng);
createGridLines(map.getBounds());
});
} // initialize
google.maps.event.addDomListener(window, "load", initialize);
function createGridLines(bounds) {
for (var i = 0; i < latPolylines.length; i++) {
latPolylines[i].setMap(null);
}
latPolylines = [];
for (var j = 0; j < lngPolylines.length; j++) {
lngPolylines[j].setMap(null);
}
lngPolylines = [];
for (var k = 0; k < lngLabels.length; k++) {
lngLabels[k].setMap(null);
}
lngLabels = [];
if (map.getZoom() < 12) {
return;
}
var north = bounds.getNorthEast().lat();
var east = bounds.getNorthEast().lng();
var south = bounds.getSouthWest().lat();
var west = bounds.getSouthWest().lng();
// define the size of the grid
var topLat = Math.ceil(north / llOffset) * llOffset;
var rightLong = Math.ceil(east / llOffset) * llOffset;
var bottomLat = Math.floor(south / llOffset) * llOffset;
var leftLong = Math.floor(west / llOffset) * llOffset;
qtrNELatLngCode = ddToQM(topLat, rightLong);
qtrNorth = qtrNELatLngCode.substring(0, 5);
qtrEast = qtrNELatLngCode.substring(5, 12);
qtrSWLatLngCode = ddToQM(bottomLat, leftLong);
qtrSouth = qtrSWLatLngCode.substring(0, 5);
qtrWest = qtrSWLatLngCode.substring(5, 12);
for (var latitude = bottomLat; latitude <= topLat; latitude += llOffset) latPolylines.push(new google.maps.Polyline({
path: [
new google.maps.LatLng(latitude, leftLong), new google.maps.LatLng(latitude, rightLong)],
map: map,
geodesic: true,
strokeColor: "#0000FF",
strokeOpacity: 0.1,
strokeWeight: 1
}));
for (var longitude = leftLong; longitude <= rightLong; longitude += llOffset) lngPolylines.push(new google.maps.Polyline({
path: [
new google.maps.LatLng(topLat, longitude), new google.maps.LatLng(bottomLat, longitude)],
map: map,
geodesic: true,
strokeColor: "#0000FF",
strokeOpacity: 0.1,
strokeWeight: 1
}));
if ((map.getZoom() < 16)) {
for (var l = 0; l < lngLabels.length; l++) {
lngLabels[l].setMap(null);
}
lngLabels = [];
return;
} // set lngLabels to null
for (var x = 0; x < latPolylines.length; ++x) {
for (var y = 0; y < lngPolylines.length; ++y) {
var latLng = new google.maps.LatLng(latPolylines[x].getPath().getAt(0).lat(),
lngPolylines[y].getPath().getAt(0).lng());
var qtrLatLng = ddToQM(latLng.lat(), latLng.lng());
Does the line touch this grid? I would think that at point of drawing the vertices, I would test to see if the line (knowing the (latlng,latlng)).
lngLabels.push(new google.maps.Marker({
map: map,
position: latLng,
icon: {
url: "https://chart.googleapis.com/chart?"
+ "chst=d_bubble_text_small&chld=bbbr|"
+ qtrLatLng
+ "|FFFFFF|000000",
anchor: new google.maps.Point(126, 42)
}
}));
}
}
} // end createGridLines
function getQtrMinTouched(oLat,oLng, fLat,fLng){
// Lost and confused here
}
function ddToQM(alat, alng) {
var latResult, lngResult, dmsResult;
alat = parseFloat(alat);
alng = parseFloat(alng);
latResult = "";
lngResult = "";
latResult += getDms(alat);
lngResult += getDms(alng);
dmsResult = latResult + lngResult;
// Return the resultant string.
return dmsResult;
}
function getDms(val) {
// Required variables
var valDeg, valMin, valSec, interimResult;
var qtrMin;
val = Math.abs(val);
// ---- Degrees ----
valDeg = Math.floor(val);
valMin = Math.floor((val - valDeg) * 60);
valSec = Math.round((val - valDeg - valMin / 60) * 3600 * 1000) / 1000;
if (valSec == 60) {
valMin += 1;
valSec = 0;
}
if (valMin == 60) {
valMin += 1;
valSec = 0;
}
interimResult = valDeg + "";
if (valMin < 10) {
valMin = "0" + valMin;
}
interimResult += valMin + "";
switch (valSec) {
case 0 :
qtrMin = "D";
break;
case 15 :
qtrMin = "C";
break;
case 30 :
qtrMin = "B";
break;
case 45 :
qtrMin = "A";
break;
}
interimResult += qtrMin;
return interimResult;
}
</script>
</body>
</html>

Kineticjs object binding

I'm creating buttons and label from arrays via loop. I assign layer.id and layer.name to the buttons and labels. What I would like to do when button is pressed, is to draw text, describing the button color, on the appropriate line. The problem is when the button is clicked, the appropriate label is positioned , but only to the last label position and when another button is clicked the caption is written over the last caption. I want to find/assign the appropriate label using l.find("." + v2) I'm using the same function for other parts of the script and the binding works.
var s = new Kinetic.Stage({container: 'toolpanel', width:500, height:700});
var l = new Kinetic.Layer();
var cp3 = new Kinetic.Rect({x: 100,y: 10,width: 400,height:700, stroke:'black', draggable:true});
var db = [];
db.push("red_Glove Type:");
db.push("blue_Glove Type:");
db.push("black_Throws:");
var lx = 50;
for (var i = 0;i < db.length;i++){ var ser = db[i]; var sdb = ser.split("_"); v1 = sdb[0]; v2 = sdb[1];
var box = new Kinetic.Rect({x: lx+=20 , y:5, fill: v1, id: v2, name:v2, height: 30, width:30});
l.add(box); lx+=30; l.draw();
var posY = box.getPosition().y;
box.on('mousedown', (function(v1,v2){ return function(){
var check = l.find("." + "v2");
var caption = new Kinetic.Text({
x: 230,
y:posY ,
fontSize: 16,
text: v1,
id:v2,
draggable: true,
fill:v1
});
caption.setText(v1);
l.add(caption); l.draw();
}})(v1,v2),false);
}
var desc = new Kinetic.Text({x: cp3.getWidth()/ 2,y: 20,text: 'Your Personalization',fontSize: 16,fontFamily: 'arial',fill: 'black',padding: 4});
l.add(desc);
s.add(l);
var odesc = [];
odesc.push("Glove Type:_20");
odesc.push("Glove Series:_40");
odesc.push("Glove Positons:_60");
odesc.push("Throws:_80");
odesc.push("Glove Back Style:_100");
odesc.push("Hand Size:_120");
var ly = 20;
for (var s = 0; s < odesc.length; s++){
var db = odesc[s];
var sdb = db.split("_");
var text = sdb[0];
var label = new Kinetic.Text({
x: 100,
y: ly+=50,
text: text,
fontSize: 16 ,
id: text,
fontFamily: 'arial',
fill: 'black',
padding: 1,
align: 'left'
);
l.add(label); ly += 10;
var posY = label.getPosition().y;
} l.draw();
Please checkout shortened scriptjsfiddle

Rectangular Overlays appearing only after dragging the map

I have a lot of markers and I m using markerClusterer to display them on the map.Additionally on click of a checkbox I need to display a rectangular overlay (title) near all these markers.
I have written 2 functions as follows for creating the overlay and deleting it.
function createLabel(posi,name){
posicion = etiquetaNombre.length;
etiquetaNombre[posicion] = name;
var label = new Label({
position:posi,
map: map,
text:name
});
rectangleNombre[posicion]=label;
rectangleNombre[posicion].setMap(map);
console.log("add: etiquetaNombre",etiquetaNombre);
myfun();
}
function deletelabel(name){
for(var i = 0; i < etiquetaNombre.length; i++){
if(etiquetaNombre[i] == name){
rectangleNombre[i].setMap(null);
rectangleNombre.splice(i, 1);
etiquetaNombre.splice(i, 1);
}
}
console.log("delete marker"+name);
console.log("delete: etiquetaNombre",etiquetaNombre);
myfun();
}
I m invoking the createLabel function as follows:
var markerImage = new google.maps.MarkerImage(imageUrl,
new google.maps.Size(24, 32));
var latLng = new google.maps.LatLng(40, -100);
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(40, -100),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < 10; ++i) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude);
var div=document.createElement('div');
var marker = new google.maps.Marker({
position: latLng,
draggable: false,
map: map,
title:"marker"+i
});
posi=marker.position;
name=marker.title;
createLabel(latLng,name);
markers.push(marker);
}
markerClusterer = new MarkerClusterer(map, markers);
Since I am using markerClusterer I had to customize it for my above requirement.I had done it as below.
Cluster.prototype.addMarker = function(marker) {
/// some lines
if (len < this.minClusterSize_ && marker.getMap() != this.map_) {
// Min cluster size not reached so show the marker.
marker.setMap(this.map_);
posi=marker.position;
name=marker.title;
createLabel(posi,name);
}
if (len == this.minClusterSize_) {
// Hide the markers that were showing.
for (var i = 0; i < len; i++) {
this.markers_[i].setMap(null);
name=this.markers_[i].title;
deletelabel(name);
}
}
if (len >= this.minClusterSize_) {
marker.setMap(null);
name=marker.title;
deletelabel(name);
}
this.updateIcon();
return true;
};
The myfun() is called on click of check box is as below.
function myfun(){
var element=document.getElementById('id1');
if(element.checked){
for(var i = 0; i < etiquetaNombre.length; i++){
var div = document.getElementById('normal-'+etiquetaNombre[i]);
if(div!=null){
div.style.display = "";
}
}
console.log("in my fun element checked",etiquetaNombre);
}
google.maps.event.addListener(map, 'bounds_changed', function () {
if(element.checked){
for(var i=0; i<etiquetaNombre.length; i++){
var div = document.getElementById('normal-'+etiquetaNombre[i]);
if(div!=null){
div.style.display = "";
}
}
}
});
}
The problem which I m facing here is that on zooming when the clustered markers are disintegrated the rectangular overlays do not appear for them.But on simply dragging the map it appears.Can anybody guide what I m doing wrong here.
[Edited]
function createLabel(xCenter , yCenter, nombre,banderaPersonalizada){
posicion = etiquetaNombre.length;
etiquetaNombre[posicion] = nombre;
var RectangleBounds = new google.maps.LatLngBounds(new google.maps.LatLng(yCenter,xCenter), new google.maps.LatLng((yCenter+1),(xCenter+1)));
rectangleNombre[posicion] = new RectangleNombre(RectangleBounds);
rectangleNombre[posicion].setMap(map);
}
function RectangleNombre(bounds, opt_weight, opt_color) {
this.bounds_ = bounds;
this.weight_ = opt_weight || 2;
this.color_ = opt_color || "#888888";
}
RectangleNombre.prototype = new google.maps.OverlayView();
RectangleNombre.prototype.onAdd = function(map) {
var idDiv = "normal-"+etiquetaNombre[posicion];
var div = document.createElement("div");
div.id = idDiv;
div.innerHTML = '<span style=" color:blue; font-family:arial; font-size:7.5pt; font-weight:900" > '+etiquetaNombre[posicion]+'</span>';
div.style.position = "absolute";
console.log("banderaCheckEtiqueta"+banderaCheckEtiqueta);
if(banderaCheckEtiqueta){
div.style.display = "";
} else {
div.style.display = "none";
}
this.getPanes().mapPane.appendChild(div);
this.map_ = map;
this.div_ = div;
}
RectangleNombre.prototype.draw = function() {
var proj = this.getProjection();
var c1 = proj.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var c2 = proj.fromLatLngToDivPixel(this.bounds_.getNorthEast());
this.div_.style.width = "0px";
this.div_.style.height = "0px";
this.div_.style.left = c1.x - 12;
this.div_.style.top = c1.y + 2;
}

Categories

Resources