Hide / Remove Specific GoogleMapsOverlay From Google Map - javascript

I have used geojson files into google map by multi selection . but when i try to remove overlay , it is not working .this is my code to used for add and remove.
i need to know how to remove selected geojson file from map
var deckOverlay ;
deckOverlay = new deck.GoogleMapsOverlay({
layers: [
new deck.GeoJsonLayer({
id: 'layerId',
data: 'path of geojson file',
filled: true,
pointRadiusMinPixels: 2,
opacity: 0.5,
pointRadiusScale: 2000,
getFillColor: f => (f.properties.COLOR),
wireframe: true,
pickable: true,
}), +
new deck.ArcLayer({
id: 'arcs',
data: Layer_Id,
dataTransform: d => d.features.filter(f => f.properties.scalerank < 4),
getSourcePosition: f => [-0.4531566, 51.4709959], // London
getTargetPosition: f => f.geometry.coordinates,
getSourceColor: [0, 128, 200],
getTargetColor: [200, 0, 80],
getWidth: 1
})
]
});
if (checked) {
deckOverlay.setMap(map); // Set multiple overlays working
}
else {
deckOverlay.setMap(null); // Remove Option Not Working
deckOverlay = null;
}

By using Data Layer .
To load map
map.data.loadGeoJson(Layer_Id);
To Remove Specific Layer
map.data.forEach(function (feature) {
if (feature.getProperty('myprop') == myprop) {
map.data.remove(feature);
}
});
To Remove All Layers
map.data.forEach(function (feature) {
map.data.remove(feature);
});
FYI , use color codes as HEX in json file not RGB or RGBA

Related

How to display information using Overlay in Openlayers?

I had a vector in my map with an image but ned to use gif instead static image so i exchanged o.layer.vector for ol.Overlay, it displays my gif but I can't get any way to add it to my layerSwitcher because overlay doesn't have title property, also with vector i could display some information using forEachFeaturePixel but now i cant. Is there any way to add my overlay to layerSwitcher and display information clicking on it?
This is what i had:
lastPoint = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature(
new ol.geom.Point(
ol.proj.fromLonLat(lastCoordinates, map.getView().getProjection())
)
)]
}),
visible: true,
title: "Evento sísmico",
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
size: [30, 28],
offset: [0.2, 0.2],
scale: 1,
src: "assets/img/red-point.png"
}),
}),
})
addEarthqPoint = (e, map, clickedCoordinate, date, time, depth, magnitude, overlayLayerEarthq) => {
map.forEachFeatureAtPixel(e.pixel, () => {
overlayLayerEarthq.setPosition(clickedCoordinate);
overlayTitleEarthq.innerHTML = "Detalle de evento: "
overlayFeatureDate.innerHTML = "Fecha: " + date;
overlayFeatureTime.innerHTML = "Hora (UTC-5): " + time;
overlayFeatureDepth.innerHTML = "Profundidad: " + depth + " km";
overlayFeatureMagnitude.innerHTML = "Magnitud: M " + magnitude;
}, {
layerFilter: (layerCandidate) => {
return layerCandidate.get("title") === "Evento sísmico";
}
});
}
mapClicked = (overlayLayer, overlayLayerEarthq) => {
map.on("click", function (e) {
const clickedCoordinate = e.coordinate;
overlayLayer.setPosition(undefined);
overlayLayerEarthq.setPosition(undefined);
/* using preview values to use into function */
addEarthqPoint(e, map, clickedCoordinate, lastDate, lastTime, lastDepth, lastMagnitude, overlayLayerEarthq);
});
}
This is my new Overlay:
lastPoint = new ol.Overlay({
position: ol.proj.fromLonLat(lastCoordinates, map.getView().getProjection()),
positioning: 'center-center',
element: document.getElementById('new-gif'),
stopEvent: false
});
Or is there any better way to use a gif instead an image?

How to undo or delete point interaction in openlayers

Let's say that we added a point into to the map by using the code below:
const addInteraction = (source) => {
draw = new ol.interaction.Draw({
source: source,
type: "Point",
style: new ol.style.Style({
fill: fillStyle,
stroke: strokeStyle,
image: circleStyle,
}),
});
map.addInteraction(draw);
draw.setActive(false);
draw.on("drawend", (_event) => {
draw.setActive(false);
});
};
After clicking the left click this code add point into the map but I want to add an undo option or delete option for that point. Removing interaction did not work. How can I do this?

How to get the markers details in the drawn polygon?

The markers will be added dynamically using firebase.
map.loadImage(
AddressIcon,
function(error, image) {
if (error) throw error;
map.addImage(id + 'address', image);
map.addSource(id + 'point', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
features
]
}
});
map.addLayer({
'id': id + "addresses-layer",
'type': 'symbol',
'source': id + 'point',
'layout': {
'icon-image': id + 'address',
'icon-size': 1
}
});
});
draw = new MapboxDraw({
displayControlsDefault: false,
userProperties: true,
controls: {
polygon: true,
trash: true
},
});
map.addControl(draw, 'bottom-left');
map.addControl(new mapboxgl.NavigationControl());
map.addControl(new mapboxgl.FullscreenControl());
map.on('draw.create', updateDrawArea);
map.on('draw.delete', updateDrawArea);
map.on('draw.update', updateDrawArea);
const updateDrawArea = (e) => {
var data = draw.getAll();
console.log(data);
}
I have the polygon drawing system on the map. I need to get all of the added layers/markers after draw the polygon around the markers. I need to do this using mapbox-gl-js if possible. If not is there any alternatives?
Yes, it is possible through Turf.js.
Turf.js exposes functions such as pointsWithinPolygon, that allow us to specify marker points and polygon coordinates, and returns a list of markers that inside the specified polygon.
For example:
var pointsWithinPolygon = require("#turf/points-within-polygon")
const turf = require('#turf/turf');
var points = turf.points([
[-46.6318, -23.5523],
[-46.6246, -23.5325],
[-46.6062, -23.5513],
[-46.663, -23.554],
[-46.643, -23.557]
]);
var searchWithin = turf.polygon([[
[-46.653,-23.543],
[-46.634,-23.5346],
[-46.613,-23.543],
[-46.614,-23.559],
[-46.631,-23.567],
[-46.653,-23.560],
[-46.653,-23.543]
]]);
var ptsWithin = turf.pointsWithinPolygon(points, searchWithin);
console.log(ptsWithin)
You can refer to this tutorial that explains how we can use turf.js along-side mapbox-gl-draw.

Display popup with multiple layers - openlayers

I am using geoserver and openlayers to display popup by clicking I have displayed popup with one layer. But I couldn't display popup when I have multiple layers.
map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Group({
layers: [
new ol.layer.Group({
layers: [
new ol.layer.Tile({
source: new ol.source.Stamen({
layer: 'baselayer'
})
}),
new ol.layer.Image({
title:'Sometitle',
source: new ol.source.ImageWMS(
{
ratio:1,
url:"http://localhost:wp/wms",
params:{
'LAYERS':'layer:layername',
}
})
}),
new ol.layer.Image({
title:'sometitle2',
source: new ol.source.ImageWMS(
{
ratio:1,
url:"http://localhost:wp/wms",
params:{
'LAYERS':'layer:layername',
}
})
}),
Then using the popup codes,
//Scripts for popup
var popup = new ol.Overlay.Popup();
map.addOverlay(popup);
//Displaying popup on click
map.on('singleclick', function(evt) {
console.log("In singleClick");
//Check for visible layers
var data = [];
layer = map.getSource(); //
var url = layer.getGetFeatureInfoUrl(
evt.coordinate, viewResolution, view.getProjection(),
reqwest({
url: url,
type: 'json',
}).then(function (data) {
if (data.features.length == 0) {
popup.hide(); //If user clicks outside
return;
}
for (var i = 0; i < data.features.length; i++)
{
console.log("In for");
var feature = data.features[i]; //Read features of JSON array
var props = feature.properties; //Read properties of feature array
var data1 = [];
var data2 = [];
Finally after all codes for popup(That worked for me to display popup for single layer) I used this line to render my popup.
popup.show(evt.coordinate,popup);
If you find it easier to have separate layers, e.g. in the GIS StackExchange question you only display bedrock geology:
source: new ol.source.ImageWMS({
url: 'http://ogc.bgs.ac.uk/cgi-bin/BGS_Bedrock_and_Superficial_Geology/wms',
params: {
'FORMAT': 'image/png',
'LAYERS': 'GBR_BGS_625k_BLS',
'TRANSPARENT': 'TRUE'
},
attributions: bgsAttrib,
}),
in an info request you can specify other layers to query, so you could get bedrock and superficial geology in one popup:
source.getGetFeatureInfoUrl( evt.coordinate,
view.getResolution,
view.getProjection(),
{ 'QUERY_LAYERS': 'GBR_BGS_625k_BLS,GBR_BGS_625k_SLS',
'INFO_FORMAT': 'text/html',
'FEATURE_COUNT': '10'} );

OpenLayers 3: Forcing a vector layer to reload GeoJSON source

I'm trying to force a vector layer in OpenLayers 3 to periodically reload its data from a GeoJSON source. The GeoJSON source changes from time to time.
After many different attempts using different methods, I think this is the closest I've managed to get so far:
$(document).ready(function(){
map.once("postcompose", function(){
//start refreshing each 3 seconds
window.setInterval(function(){
var source = testLayer.getSource();
var params = source.getParams();
params.t = new Date().getMilliseconds();
source.updateParams(params);
}, 3000);
});
});
However this is giving me the following (every 3 seconds of course):
Uncaught TypeError: source.getParams is not a function
Here's all of the other code I'm using to load and display the GeoJSON file. The other layers in the map are loaded in the same way:
var testSource = new ol.source.Vector({
url: '/js/geojson/testfile.geojson',
format: new ol.format.GeoJSON()
});
...
window.testLayer = new ol.layer.Vector({
source: testSource,
style: function(feature, resolution) {
var style = new ol.style.Style({
fill: new ol.style.Fill({color: '#ffffff'}),
stroke: new ol.style.Stroke({color: 'black', width: 1}),
text: new ol.style.Text({
font: '12px Verdana',
text: feature.get('testvalue'),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.1)'
}),
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 1)',
width: 1
})
})
});
return style
}
});
...
var olMapDiv = document.getElementById('olmap');
var map = new ol.Map({
layers: [paddocksLayer,zonesLayer,structuresLayer,roadsLayer,testLayer],
interactions: ol.interaction.defaults({
altShiftDragRotate: false,
dragPan: false,
rotate: false
}).extend([new ol.interaction.DragPan({kinetic: null})]),
target: olMapDiv,
view: view
});
view.setZoom(1);
view.setCenter([0,0]);
I read somewhere else that getParams simply doesn't work on vector layers, so this error wasn't entirely unexpected.
Is there an alternative method which will reload (not just re-render) a vector layer?
Thanks in advance. I must also apologise in advance as I'll need really specific guidance with this - I'm very new to JS and OpenLayers.
Gareth
(fiddle)
You can achieve this with a custom AJAX loader (when you pass url to ol.source.Vector this is AJAX as well). Then you can reload your JSON file as you will.
You can use any AJAX library you want but this is as simple as:
var utils = {
refreshGeoJson: function(url, source) {
this.getJson(url).when({
ready: function(response) {
var format = new ol.format.GeoJSON();
var features = format.readFeatures(response, {
featureProjection: 'EPSG:3857'
});
source.addFeatures(features);
source.refresh();
}
});
},
getJson: function(url) {
var xhr = new XMLHttpRequest(),
when = {},
onload = function() {
if (xhr.status === 200) {
when.ready.call(undefined, JSON.parse(xhr.response));
}
},
onerror = function() {
console.info('Cannot XHR ' + JSON.stringify(url));
};
xhr.open('GET', url, true);
xhr.setRequestHeader('Accept','application/json');
xhr.onload = onload;
xhr.onerror = onerror;
xhr.send(null);
return {
when: function(obj) { when.ready = obj.ready; }
};
}
};

Categories