What do I replace PointerEvent in OpenLayers 5 with in OL 6? - openlayers-5

Trying to upgrade from OL5.3 to OL6.1 but not sure how to fix this yet.
https://github.com/openlayers/openlayers/blob/master/changelog/upgrade-notes.md#olinteractionmodifyevent-changes
That covers the renaming of MapBrowserPointerEvent
import PointerEvent from 'ol/pointer/PointerEvent.js';
import MapBrowserPointerEvent from 'ol/MapBrowserPointerEvent.js';
...
// simulate a click on the map
let event = new PointerEvent('singleclick', {
clientX: xy[0],
clientY: xy[1],
shiftKey: false
});
map.handleMapBrowserEvent(new MapBrowserPointerEvent('singleclick', map, event));
but not sure what needs to happen with new PointerEvent() and it does seem to be covered in the changelog.
Thanks,
-Steve

This seems to work on OL6:
import MapBrowserEvent from 'ol/MapBrowserEvent';
let event = {
coordinate: pnt,
map: map,
target: 'map',
pixel: xy,
type: 'singleclick'
};
map.dispatchEvent(event);

Related

Open Layers 5.3.0 project, problem with Point customization

I'm learning openstreetmaps and openlayers. I started with application approach (Parcel + openlayers). Most of examples you find here, that could possibly help me are used with older code, which as I understand does not support all features such as Clusters and other stuff. I tried them and was not able to make it work with new environment (of cause it was not just copy-past). My question is relatively simple, I want to customize Features with [Points][1], docs say I can set their style by [setStyle][2] they also have example where it actually works. I used that example to start but whatever style I describe in there I see no new point on a map, and there are none any errors in Parsel or in browser console. If I do not use setStyle I see my point on a map. I tried different ways to set a style but none of them actually worked for me.
I do it like that, first I set style:
var iconStyle = new Style({
fill: 'red'
});
After that I add point to features array like that
features.push( new Feature({
geometry: new Point(coordinates),
address: 'Адрес точки 2',
ordererName: 'Имя человека 2',
})
);
and afterwards I set a style for a point:
features[1].setStyle(iconStyle);
and put all of that into map:
var source = new VectorSource({
features: features
});
var vectorLayer = new VectorLayer({
source: source
});
var raster = new TileLayer({
source: new OSM()
});
//EPSG:3857 - web
//EPSG:4326 - GPS
var map = new Map({
layers: [
raster,
//source,
//clusters,
vectorLayer
],
target: 'map',
view: new View({
center: transform(map_center, 'EPSG:4326', 'EPSG:3857'),
zoom: 13
})
});
So my question is how to set a style for a point and actually see on a map? If you also capable to suggest how to add such a custom Point on click on a map after you created a map with layers and points that is highly appreciated. Thanks in advance.
Your style setup isn't complete, to display a point your need to style it as an image, for example a red filled circle
var iconStyle = new Style({
image: new CircleStyle({
radius: 10,
fill: new Fill({
color: 'red'
})
})
});
If adding a feature after creating the map it might look like this:
map.on('click', function(event) {
var feature = new Feature({
geometry: new Point(event.coordinate)
...
...
});
feature.setStyle(...);
source.addFeature(feature);
});

Mapbox GL directions plugin hiding search origin destination box

I am using Mapbox GL directions plugin inside my app where I set the origin on map load and set driving destination upon user click on any location on the map. I am now trying to remove the top left search origin / destination box yet after extensive research can't figure out how to do so, can someone please help by telling me how to do so? Thanks.
Code I am using in my app below:
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v8',
center: [userCoordinates.coords.longitude, userCoordinates.coords.latitude],
zoom: 15
});
var directions = new mapboxgl.Directions({
unit: 'metric',
profile: 'driving'
});
map.addControl(directions);
directions.setOrigin([userCoordinates.coords.longitude, userCoordinates.coords.latitude]);
map.on('click', function(e) {
var features = map.queryRenderedFeatures(e.point, { layers: ['gsLayer'] });
if (!features.length) {
return;
}
var feature = features[0];
directions.setDestination([feature.geometry.coordinates[0], feature.geometry.coordinates[1]]);
});
I couldn’t figure this out either since there is no documentation, but finally I read through the mapbox-gl-directions.js file and I think I found out how to do it.
In your example, you should embed the controls like this in order to remove the origin / destination box:
var directions = new mapboxgl.Directions({
unit: 'metric',
profile:'driving',
container:'directions', // Specify an element thats not the map container.
// UI controls
controls: {
inputs: false,
instructions: true
}
});
map.addControl(directions);
I'll assume you are using Mapbox GL Javascript, and looking at this example it appears map.addControl(new mapboxgl.Directions()); is what is adding the controller. Within your code you gave you also have this map.addControl(directions);. Try removing it and see what happens.
Hope this helps!

MapBox - Add a clusterGroup clickable with Layer Control

I'm still learning and I'm a bit stuck. I may be trying to do to much at once. I have a MapBox map working great with a clickable layer menu taken from examples on the MapBox site. I also have a MarkerClusterGroup which also works and is always visible on the map. Is there a way I could somehow have the MarkerClusterGroup clickable on/off just like layers identified in var overlays = { ...
Below is the code that I think needs the help:
var layers = {
Streets: L.mapbox.tileLayer('mapbox.streets').addTo(map),
Satellite: L.mapbox.tileLayer('mapbox.satellite'),
Light: L.mapbox.tileLayer('mapbox.light'),
};
var overlays = {
DataA: L.mapbox.featureLayer().loadURL('/data/ctsnew.geojson'),
DataB: L.mapbox.featureLayer().loadURL('/data/selectZipcodes.geojson'),
};
// Since featureLayer is an asynchronous method, we use the `.on('ready'`
// call to only use its marker data once we know it is actually loaded.
Markers: L.mapbox.featureLayer('examples.map-h61e8o8e').on('ready', function(e) {
// The clusterGroup gets each marker in the group added to it
// once loaded, and then is added to the map
var clusterGroup = new L.MarkerClusterGroup();
e.target.eachLayer(function(layer) {
clusterGroup.addLayer(layer);
});
map.addLayer(clusterGroup);
});
Could be something as simple as misuse of brackets. Thanks in advance.
You have to include your Marker Cluster Group in your overlays object. For example you could instantiate it just before defining overlays, even if your Cluster Group is empty for now.
Then you fill it once it has downloaded its data.
var layers = {
Streets: L.mapbox.tileLayer('mapbox.streets').addTo(map),
Satellite: L.mapbox.tileLayer('mapbox.satellite'),
Light: L.mapbox.tileLayer('mapbox.light'),
};
var clusterGroup = L.markerClusterGroup();
var overlays = {
DataA: L.mapbox.featureLayer().loadURL('/data/ctsnew.geojson'),
DataB: L.mapbox.featureLayer().loadURL('/data/selectZipcodes.geojson'),
Markers: clusterGroup
};
// Since featureLayer is an asynchronous method, we use the `.on('ready'`
// call to only use its marker data once we know it is actually loaded.
L.mapbox.featureLayer('examples.map-h61e8o8e').on('ready', function(e) {
// The clusterGroup gets each marker in the group added to it
// once loaded, and then is added to the map
e.target.eachLayer(function(layer) {
clusterGroup.addLayer(layer);
});
map.addLayer(clusterGroup); // use that line if you want to automatically add the cluster group to the map once it has downloaded its data.
});

OL3: Setting map view center to geolocation.getCurrentPosition doesn't work

When the application starts, I want to center the map view on the users current position. I have tried two different approaches and can't get them work. The first one worked properly in leaflet, but in the development process I have decided to use OL3 instead.
First approach (worked in leaflet):
var myProjectionName = "EPSG:25832";
proj4.defs(myProjectionName,
"+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs");
var centerPosition;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (pos) {
centerPosition =
ol.proj.transform(
[position.coords.longitude,
position.coords.latitude],
'EPSG:4326',
myProjectionName);
},
function (err) {centerPosition = [724844,6178000];},
{
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 1000
});
}
My second approach was using the ol.Geolocation class:
var proj1 = ol.proj.get(myProjectionName);
var geolocation = new ol.Geolocation({
projection: proj1
});
var centerPosition= geolocation.getPosition();
The center position is used in creating the view/map object:
var map = new ol.Map({
target: 'map',
logo : false,
layers: [ GSTGroup, OVLGroup, SheatLayer],
view: new ol.View({
projection: myProjectionName,
center: centerPosition,
resolutions : AVLresolutions,
resolution : 2
})
});
I have some suspecions that the cause of the problem is the projection, but on the other hand the projection works properly in transforming layers (WMTS, Vector), source from Geojson in different coordinatesystem and in ol.control.MousePosition.
I am using Firefox 32.0.3 and the geolocator plugin to development/test
Working example in http://jsfiddle.net/AndersFinn/ak4zotn8/
Add after the map declaration the following (tested):
var proj1 = ol.proj.get(myProjectionName);
var geolocation = new ol.Geolocation({
projection: myProjectionName,
tracking: true
});
geolocation.on('change', function(evt) {
console.log(geolocation.getPosition());
map.getView().setCenter(geolocation.getPosition());
});
The most important part is tracking: true in the code: it means you check regularly the position to center.
The second important part is to bind event on geolocation object (an instance of ol.Geolocation)
See in the official examples the geolocation samples and the API docs to make some changes depending of your requirements

Working with openlayers and typescript classes

/// <reference path="openlayers.d.ts" />
class MapComponent {
element: HTMLElement;
map: OpenLayers.Map;
constructor(element: HTMLElement) {
// Setup our map object
this.element = element;
this.map = new OpenLayers.Map(this.element);
}
init() {
// Setup our two layer objects
var osm_layer_map = new OpenLayers.Layer.OSM("OSM");
// Add layers to the map
this.map.addLayers([osm_layer_map]);
// Add a layer switcher control
this.map.addControl(new OpenLayers.Control.LayerSwitcher({}));
// Zoom the map to the max extent
if (!this.map.getCenter()) {
this.map.zoomToMaxExtent();
}
}
}
window.onload = () => {
var el = document.getElementById('map');
var mc = new MapComponent(el);
mc.init();
}
I have the above piece of code to work with a simple HTML file with only 1 of ID, 'map' with style: height and width # 500px.
I have tried several other ways to get the map to display but so far all i got was a white page (blank).
Can anybody point me in the right direction?
Solutions tried so far:
using jquery with ready function
replace window.onload with a call direct from the html, <script><script/>
place document.getElementById() in the new OpenLayers.Map(here); when first creating this.map
placing the window.onload call above and below (currently)
using export class or public init() or both
As of now, I just want it to work.
Seems that creating the map with the element provided and later defining the options doesn't work.
Instead either initialize the map with options
var options = {
projection: "EPSG:3857",
maxExtent: new OpenLayers.Bounds(-200000, -200000, 200000, 200000),
center: new OpenLayers.LonLat(-12356463.476333, 5621521.4854095)
};
this.map = new OpenLayers.Map(this.element, options);
Or call this.map.render(this.element) at the end of your init method.
Also make sure your div is actually visible and has some size specified, otherwise it might be not visible...