OpenLayers => feature is null - javascript

This is my GeoJSON result. PasteBin
But when I load it, the result I get in firebug is feature is null. Why's that, are there any errors in my result? The coords in the JSON is written in projection WGS84, and in the code I also have set the externalProjection as WGS84. So why do I get the return "feature is null"?
The code I use to manage my map is :
$(document).ready(function() {
var wgs84 = new OpenLayers.Projection('EPSG:4326');
var layer = null;
var map = new OpenLayers.Map('map',{projection: wgs84});
layer = new OpenLayers.Layer.OSM( "Simple OSM Map");
var baseProjection = layer.projection;
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(10,10), 4);
map.events.register("moveend", null, function(){
if(map.zoom == 10)
{
var bounds = map.getExtent();
console.log(bounds);
var ne = new OpenLayers.LonLat(bounds.right,bounds.top).transform(map.getProjectionObject(),wgs84);
var sw = new OpenLayers.LonLat(bounds.left,bounds.bottom).transform(map.getProjectionObject(),wgs84);
var vectorLayer = new OpenLayers.Layer.Vector();
map.addLayer(vectorLayer);
$.getJSON('ajax.php?a=markers&type=json&sw=('+sw.lon+','+sw.lat+')&ne=('+ne.lon+','+ne.lat+')',function(data){
//$.getJSON('test.json',function(data){
var geojson_format = new OpenLayers.Format.GeoJSON({
'externalProjection': wgs84,
'internalProjection': baseProjection
});
vectorLayer.addFeatures(geojson_format.read(data));
});
}
});
});

Your sample OpenLayer code is working correctly, the problem is in your GeoJSON: you misspelled coordinates as "coordninates"

Related

Why the information I save in an event is being lost

good morning
I am trying to use Leaflet to paint an image and save the figures, I have created the following method to start the map:
initmap()
{
var url = 'http://kempe.net/images/newspaper-big.jpg';
var bounds = [[-26.5,-25], [1021.5,1023]];
var image = L.imageOverlay(url, bounds);
var map = new L.Map('image-map', {layers: [image], crs: L.CRS.Simple, minZoom : -5});
map.fitBounds(bounds);
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
position: 'topright',
draw: {
polyline: true,
polygon: false,
circle: false,
marker: true
},
edit: {
featureGroup: drawnItems,
remove: true
}
});
map.addControl(drawControl);
map.on(L.Draw.Event.CREATED, function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('A popup!');
}
drawnItems.addLayer(layer);
var type = e.layerType
var shape = layer.toGeoJSON()
var shape_to_json = JSON.stringify(shape);
this.currentMap = shape_to_json;
});
map.on(L.Draw.Event.EDITED, function (e) {
var layers = e.layers;
var countOfEditedLayers = 0;
layers.eachLayer(function (layer) {
countOfEditedLayers++;
});
});
}
As you can see there is an event definition for what to do when someone is drawing, (map.on(L.Draw.Event.CREATED, function (e) )
The point is that I log that method, with console.log to check what is saving in
this.currentMap = shape_to_json;
As you can see:
shape_to_json
installations-management.component.ts:120 {"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[421.202413,315.527832],[421.202413,756.416626],[988.101415,756.416626],[988.101415,315.527832],[421.202413,315.527832]]]}}
Everything seems ok. But when I click on the save button, the data of this.currentMap is missing, and in no other point is being modifidied.So, am I saving it wrong or is modified somewhere because of the event?
Thank you all !

OpenLayers 6 + Angular 8 : LineString(s) not showing up on Vector Layer (With no errors from JS)

I'm having an issue where my LineString(s) aren't showing up on the map and the console isn't giving out any errors.
I belive my code is correct but i'm not that bright when it comes to OpenLayers and i may be wrong.
This is how i add my Vector Layer to the map
var vectorLayer = new ol.layer.Vector({
name: 'trailLayer',
type: "Vector",
source: new ol.source.Vector({ format: new ol.format.GeoJSON({ featureProjection:"EPSG:3857" }) }),
zoomMin: 8,
zoomMax: 18
});
this.map.addLayer(vectorLayer);
Than this is what I do to add a new LineString
let layer;
this.map.getLayers().forEach(function (value) { if ( value.get('name') === 'trailLayer') { layer = value; } });
if(layer == null) { return; }
let coords = [[latA, lonA], [latB, lonB]];
let lineString = new ol.geom.LineString(coords);
lineString.transform('EPSG:4326', 'EPSG:3857');
var lineFeature = new ol.Feature({
name: callsign,
});
lineFeature.setGeometry(lineString);
var lineStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
width: trailWidth,
color: trailColor
})
});
lineFeature.setStyle(lineStyle);
layer.getSource().addFeature(lineFeature);
If I try to use source.GetFeatures() it shows all my features correctly, but I can't see them on the map.
Am I missing something?
P.S. Every variable is assigned correctly, nothing strange and no undefined ecc...
In OL the coordinates must be expressed as longitude first, then latitude.
Try swapping the coordinates:
let coords = [[lonA, latA], [lonB, latB]];

AngularJS id attribute in the included HTML template

In AngularJS, the id attribute from my HTML Template isn't recognized by my javascript.
For example :
index.html file :
<div ng-controller="SubwayMapController">
<div subway-map></div>
</div>
scripts.js file :
app.directive('subwayMap', function () {
return {
templateUrl: 'Views/subway-map.html'
};
});
map = new OpenLayers.Map("basicMap");
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(2.35,48.85).transform( fromProjection, toProjection); //Paris
var zoom = 12;
map.addLayer(mapnik);
map.setCenter(position, zoom );
subway-map.html file :
<div id="basicMap"></div>
When I open index page, I expect the map from Openstreetmap to be displayed but nothing happens.
Try setting up the map in the link() function of the directive. Plus, it looks like you can Map.render() using a DOMElement instead of needing an ID.
app.directive('subwayMap', function () {
return {
templateUrl: 'Views/subway-map.html',
link: function(scope, element) {
var map = new OpenLayers.Map();
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326");
var toProjection = new OpenLayers.Projection("EPSG:900913");
var position = new OpenLayers.LonLat(2.35,48.85)
.transform(fromProjection, toProjection);
var zoom = 12;
map.addLayer(mapnik);
map.setCenter(position, zoom );
map.render(element[0]);
}
};
});
put map access code in setTimeout. You are trying to access the map immediately . Angular ain't done with map rendering yet , so setTimeout is the solution.
$timeout(function(){
map = new OpenLayers.Map("basicMap");
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(2.35,48.85).transform( fromProjection, toProjection); //Paris
var zoom = 12;
map.addLayer(mapnik);
map.setCenter(position, zoom );
},10);

Remove markers out of viewport

I have to manage a map of about 80.000 markers concentrated in France.
To do that, I decided to get the bounds of the viewport and call a dynamic-JSON (with PHP) which contains the markers inside the viewport. And this on the "idle" event.
I faced a problem with this solution. Indeed, the markers which already exist was re-plotted (at the same position), which consequently weigh the map for nothing...
To solve it, the markers list before and after the JSON query are compared (thanks to jQuery), in order to plot only the new markers. And it works!
Now, I would want to remove the markers which are not currently shown on the map. Or a list of markers (I get it thanks to jQuery) designated by an ID which is also the title of the marker. So, how can a delete markers like that ? I specify that I am using MarkerManager.
Otherwise, you guess that if I do not remove these markers, they will be re-plotted in some cases... For example, you are viewing the city A, you move the map to view the city B, and you get back to the city A...
Here is the code:
var map;
var mgr;
var markers = [];
function initialize(){
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(46.679594, 2.109375)
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var mgrOptions = { borderPadding: 50, maxZoom: 15, trackMarkers: false };
mgr = new MarkerManager(map, mgrOptions);
google.maps.event.addListener(map, 'idle', function() {
mapEvent();
});
}
function mapEvent(){
if( map.getZoom() >= 8 ){
var bounds = map.getBounds();
getSupports(bounds.getNorthEast(), bounds.getSouthWest());
} else {
// Todo
}
}
var markerslistID = new Array();
var markerslistData = {};
function getSupports(ne, sw){
newMarkerslistID = new Array();
newMarkerslistData = {};
// Getting the markers of the current view
$.getJSON('./markerslist.php?nelat='+ne.lat()+'&nelng='+ne.lng()+'&swlat='+sw.lat()+'&swlng='+sw.lng(), function(data) {
for (var i = 0; i < data.points.length; i++) {
var val = data.points[i];
newMarkerslistID.push(val.id);
newMarkerslistData[val.id] = new Array(val.lat, val.lng, val.icon);
}
// List of New Markers TO PLOT
var diffNewMarkers = $(newMarkerslistID).not(markerslistID).get();
// List of Old markers TO REMOVE
var diffOldMarkers = $(markerslistID).not(newMarkerslistID).get();
// Plotting the NEW MARKERS
for( var i = 0; i < diffNewMarkers.length; i++ ){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(newMarkerslistData[diffNewMarkers[i]][0], newMarkerslistData[diffNewMarkers[i]][1]),
title : diffNewMarkers[i],
icon : './images/'+newMarkerslistData[diffNewMarkers[i]][2]+'.png'
});
mgr.addMarker(marker, 0);
}
/*****************************************
HERE WE HAVE TO REMOVE
THE MARKERS CONTAINED IN diffOldMarkers
*****************************************/
mgr.refresh();
// Switching the new list to the old, for the next event
markerslistID = newMarkerslistID;
markerslistData = newMarkerslistData;
});
}
Thank you for your help.
A one-liner to hide all markers that ar not in the current viewport.
!map.getBounds().contains(marker.getPosition()) && marker.setVisible(false);
Or,
if (map.getBounds().contains(marker.getPosition()) && !marker.getVisible()) {
marker.setVisible(true);
}
else if (!map.getBounds().contains(marker.getPosition()) && marker.getVisible()) {
marker.setVisible(false);
}

why map.setCenter is not working?

I have the below code in openlayers
<script defer="defer" type="text/javascript">
var map = new OpenLayers.Map('map');
var wms = new OpenLayers.Layer.WMS("OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0", { layers: 'basic' });
var dm_wms = new OpenLayers.Layer.WMS(
"Canadian Data",
"http://www2.dmsolutions.ca/cgi-bin/mswms_gmap",
{
layers: "bathymetry,land_fn,park,drain_fn,drainage," +
"prov_bound,fedlimit,rail,road,popplace",
transparent: "true",
format: "image/png"
}, { isBaseLayer: true }
);
var vectorLayer = new OpenLayers.Layer.Vector("Overlay");
map.setBaseLayer(vectorLayer);
OpenLayers.Geometry.Point(77.391026, 28.535516), { some: 'data' }, { externalGraphic: 'Image/map-icons/Banquet_and_Marriage_halls.png', graphicHeight: 21, graphicWidth: 21 });
var center = new OpenLayers.Geometry.Point(77.391026, 28.535516);
center.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.setCenter(new OpenLayers.LonLat(77, 28), 4);
var markers = new OpenLayers.Layer.Markers("Markers");
var ll = new OpenLayers.LonLat(77.391026, 28.535516);
var popupClass = OpenLayers.Popup.Anchored;
var popupContentHTML = '<div style="height:40px;">Hello Noida</div>';
addMarker(ll, popupClass, popupContentHTML, true);
ll = new OpenLayers.LonLat(74.613647, 30.914007);
popupClass = OpenLayers.Popup.Anchored;
popupContentHTML = '<div style="height:40px;">Hello Punjab</div>';
addMarker(ll, popupClass, popupContentHTML, true);
map.addLayers([wms, dm_wms, markers]);
var feature;
var popup = null;
function addMarker(ll, popupClass, popupContentHTML, closeBox, overflow) {
feature = new OpenLayers.Feature(markers, ll);
feature.closeBox = closeBox;
feature.popupClass = popupClass;
feature.data.popupContentHTML = popupContentHTML;
feature.data.overflow = (overflow) ? "auto" : "hidden";
var marker = feature.createMarker();
var markerClick = function (evt) {
//alert(popup);
if (popup != null)
popup.hide();
popup = this.createPopup(this.closeBox);
popup.contentSize = new OpenLayers.Size(10, 20);
map.addPopup(popup);
popup.show();
};
marker.events.register("mousedown", feature, markerClick);
markers.addMarker(marker);
}
</script>
And every thing works fine if I remove the map.setCenter(). BUt when I try to use it in my code, my map sudddenly disappears.
I also get the follwoing error in my console window:
Cannot call method 'containsLonLat' of null
I've tried every possible method on this website, but did not reach any where.. What can be the problem?
I think you put an extra Bracket in you code, try map.setCenter(new OpenLayers.LonLat(77, 28), 4); to see if it works or not.
Use leaflet https://leafletjs.com/
var map = L.map('mapid').setView([77.391026, 28.535516], 16);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attributionControl: true
}).addTo(map);
reference: https://leafletjs.com/examples/quick-start/

Categories

Resources