How to hide and show point data in Map Using Open Layer 6 - geojson

I am trying to hide and show to point data from Map. I am getting point data from Geojson format but map.removeLayer(geojson) function is not working.
my code is like :
geojson = new ol.layer.Vector({
source: new ol.source.Vector({
url: url,
format: new ol.format.GeoJSON()
}),
style: style,
});
geojson.getSource().on('addfeature', function(){
map.getView().fit(
geojson.getSource().getExtent(),
{ duration: 1590, size: map.getSize() }
);
});
if(checkvalue==1) {
map.addLayer(geojson);
}
else if(geojson) {
map.removeLayer(geojson);
}

Related

Mapbox GL JS Rails - Load GEOJSON array to markers

I am trying to integrate Mapbox into a static page, but I am having difficulty feeding the geojson array into Mapbox to generate markers procedurally. My ajax call isn’t giving an error message, but none of the geojson data appears in the console and no markers are rendered to the map. When I place some inline geojson in place of my geojson, the markers generate on the map without any problems. Any thoughts on what I have wrong here?
static_pages_controller.rb
class StaticPagesController < ApplicationController
def map
#experiences = Experience.all
#geojson = Array.new
#experiences.each do |experience|
#geojson << {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [experience.longitude, experience.latitude]
},
properties: {
name: experience.name,
address: experience.location,
:'marker-color' => '#00607d',
:'marker-symbol' => 'circle',
:'marker-size' => 'medium'
}
}
end
respond_to do |format|
format.html
format.json { render json: #geojson } # respond with the created JSON object
end
end
static_pages/map.html.erb
<div id='map' style='width: 100%; height: 750px;'></div>
<script>
$(function() {
mapboxgl.accessToken = 'pk.eyJ1IjoianJvY2tldGxhYiIsImEiOiJTOFhPc1hjIn0.jf1Gd5AeO6xVQoTA_KMhEg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
center: [-96, 37.8],
zoom: 3
});
map.on('load', function() {
$.ajax({
dataType: 'text',
url: '/map.json',
success: function(data) {
var geojson;
geojson = $.parseJSON(data);
return geojson;
// add markers to map
geojson.features.forEach(function(marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
// make a marker for each feature and add to the map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(map);
});
},
error:function() {
alert("Could not load the events");
},
});
});
});
</script>
Server Log
Started GET "/map.json" for 127.0.0.1 at 2018-02-06 16:07:27 -0800
Processing by StaticPagesController#map as JSON
Experience Load (0.3ms) SELECT "experiences".* FROM "experiences"
Completed 200 OK in 3ms (Views: 1.4ms | ActiveRecord: 0.3ms)
I ended up figuring it out! I needed to move some of the javascript around for the geojson to be fed correctly and wait for document ready and for the map to load before trying to load the markers and geojson.
Updated Javascript
$(function() {
mapboxgl.accessToken = 'pk.eyJ1IjoianJvY2tldGxhYiIsImEiOiJjajZuNnh5dm4wNTgyMndvMXNqY3lydjI4In0.gHVskGK1QuUoxm8sMwugWQ';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/jrocketlab/cjdaqnwhbb3e52sqwblieddk1',
center: [-96, 37.8],
zoom: 3
});
map.on('load', function() {
$.ajax({
dataType: 'text',
url: '/map.json',
success: function(data) {
var myjson;
myjson = $.parseJSON(data);
var geojson = {
type: 'FeatureCollection',
features: myjson
};
// add markers to map
geojson.features.forEach(function(marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
// make a marker for each feature and add to the map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(map);
});
},
error:function() {
alert("Could not load the events");
}
});
});
});

How to keep the styles of Polygon when creating KML in Openlayers 3?

When i write the features to KML. It doesn't include the styles of features. A similiar question is asked for openlayers 2. I want the code for openlayers 3. Following is the code for writing the features to the kml file
var drfeatures = drawLayerSource.getFeatures();
var format = new ol.format.KML();
var kml = format.writeFeatures(drfeatures, {featureProjection:'EPSG:3857'});
You can just add style object to the ol.format.KML();
var source = new ol.source.Vector({
url: 'city.kml',
format: new ol.format.KML({
projection: 'EPSG:3857',
extractStyles: false
})
});
function styleFunction(feature) {
var style = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 4
})
})
return [style];
}
var layer = new ol.layer.Vector({
source: source,
style: styleFunction
});
map.addLayer(layer);

How to use features from Geojson in openlayers3?

I am using openlayers3 and i want to bring my features from feature.json, it seems when my map is loded I can get the feature file from network as xhr request but i am not able to see my polygons on map. Here below is my code
function showMap() {
var vector = new ol.layer.Vector({
projection: 'EPSG:5650',
source: new ol.source.Vector({
format: new ol.format.GeoJSON(),
projection: 'EPSG:5650',
url: 'feature.json'
})
});
var map = new ol.Map({
target: 'tilemap',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
layers: [
new ol.layer.Image({
source: new ol.source.ImageWMS({
url: 'http://www.geodaten-mv.de/dienste/adv_dop',
crossOrigin: null,
projection: 'EPSG:5650',
params: {
VERSION: '1.3.0',
LAYERS: 'mv_dop',
FORMAT: 'image/jpeg',
CRS: 'EPSG:5650'
}
})
}),vector
],
view: new ol.View({
projection: 'EPSG:5650',
center: [33355494, 5983295],
zoom: 10
})
});
DisplayTilesServices.setMap(map);
}
I was using olderversion of openlayers and now instead of Using url in source, now I am using features and it works!! see the code below
$http.get('feature.geojson').then(function(res){
var format = new ol.format.GeoJSON();
source=new ol.source.Vector({
projection: 'EPSG:5650',
features:format.readFeatures(res.data)
});
var vectorLayer = new ol.layer.Vector({
source: source
});
map.addLayer(vectorLayer);
},function(){})

OpenLayers 3 popup with external geojson

Trying to get a popup working with my geojson data. Error states $(element).popover is not a function. I'm thinking it has something to do with not being able to read the features, even though they display properly.
Using the latest version of OpenLayers and jquery:
http://openlayers.org/en/v3.12.1/build/ol.js
https://code.jquery.com/jquery-1.11.2.min.js
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: 'http://services5.arcgis.com/GfwWNkhOj9bNBqoJ/ArcGIS/rest/services/nyad/FeatureServer/0/query?where=1=1&outFields=*&outSR=4326&f=geojson',
format: new ol.format.GeoJSON()
}),
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
}),
vectorLayer
],
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([-73.95, 40.7]),
zoom: 11
})
});
var element = document.getElementById('popup');
var popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false
});
map.addOverlay(popup);
// display popup on click
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
if (feature) {
popup.setPosition(evt.coordinate);
console.log(evt.coordinate);
$(element).popover({
'placement': 'top',
'html': true,
'content': feature.get('AssemDist')
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});
You are add bootstrap
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

How to set zoom and center automatically based on GeoJSON features

I load some features from .json file, and would like to automatically set view wuth zoom to see all loaded features. I user OpenLayers version 3.
Here's what I have:
var gjsonFile = new ol.layer.Vector({
source: new ol.source.GeoJSON({
url: 'map.json',
projection: 'EPSG:3857'
})
})
});
var map = new ol.Map({
view: new ol.View({
center: ol.proj.transform([-77.0087,38.8691], 'EPSG:4326', 'EPSG:3857'),
zoom: 12
}),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
gjsonFile
],
target: 'map1'
});
Vector sources have a #getExtent() method that gives you the extent of all features currently loaded in the source. To set the map's view to that extent as soon as the file is loaded, add the following code:
var source = gjsonFile.getSource();
var onChangeKey = source.on('change', function() {
if (source.getState() == 'ready') {
source.unByKey(onChangeKey);
map.getView().fitExtent(source.getExtent(), map.getSize());
}
});

Resources