Display my Mapbox map in Openlayers 5.3.0? - mapbox

I am trying to display my custom map from Mapbox in Openlayers 5.3.0. I am trying to follow the example HERE.
I am able to show the standard Mapbox background, but as soon as I change to my personal map style it breaks and shows a blank screen...
Here is example code:
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic3ZlbnB0IiwiYSI6ImNqc2Vxa3Q5MzBqcTAzeW1kOWRiajV4ZzYifQ.xpDqTM6B41sS6QjZPwb6yQ' //this works
/*
url: 'https://api.mapbox.com/styles/v1/svenpt/cjsbq6vq716ye1fpgw10kvitp.html?access_token=pk.eyJ1Ijoic3ZlbnB0IiwiYSI6ImNqc2Vxa3Q5MzBqcTAzeW1kOWRiajV4ZzYifQ.xpDqTM6B41sS6QjZPwb6yQ' //this doesn't work
url: 'https://api.mapbox.com/styles/v1/svenpt/cjsbq6vq716ye1fpgw10kvitp.html/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic3ZlbnB0IiwiYSI6ImNqc2Vxa3Q5MzBqcTAzeW1kOWRiajV4ZzYifQ.xpDqTM6B41sS6QjZPwb6yQ' //this doesn't work either
*/
})
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});

Credits to Mike for the answer!
The correct url is:
url: 'https://api.mapbox.com/styles/v1/svenpt/cjsbq6vq716ye1fpgw10kvitp/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic3ZlbnB0IiwiYSI6ImNqc2Vxa3Q5MzBqcTAzeW1kOWRiajV4ZzYifQ.xpDqTM6B41sS6QjZPwb6yQ'
I had to delte the .html from:
url: 'https://api.mapbox.com/styles/v1/svenpt/cjsbq6vq716ye1fpgw10kvitp.html/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic3ZlbnB0IiwiYSI6ImNqc2Vxa3Q5MzBqcTAzeW1kOWRiajV4ZzYifQ.xpDqTM6B41sS6QjZPwb6yQ'

Related

Error with Mapbox GL integration when adding markers: "Cannot read property 'coordinates' of undefined"

I've been working on creating a dynamically updated Mapbox GL integration inside Webflow's CMS. I've succeeded in creating an array of features that can be read by Mapbox's API, but these features won't show on the map because the coordinates are not being read by the function that creates the map markers.
I receive the following error Cannot read property 'coordinates' of undefined at map-test-page:139 which is where a longitude and latitude is assigned to the current marker via this line: .setLngLat(marker.geometry.coordinates)
Partial solution was found here, but the code I've integrated into my site doesn't have featuresIn or featuresAt functions which seem to be the only way to include a includeGeometry: true parameter.
I'm curious if I need to rethink how I've created markers and do something with a function like map.on('click', ...) reference here.
Here is a minimal version that reproduces my issue.
If you're familiar with the Webflow interface you can view a read-only version of the site.
Any help would be greatly appreciated!
Here is the Mapbox script I'm using on the page:
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/strawpari/ckp2nu3dw6cwu17nt4kqwf1vv',
center: [-13.723969, 48.360542],
zoom: 2,
pitch: 0,
bearing: 0,
antialias: true,
interactive: true
});
var geojson = {
type: 'FeatureCollection',
features: farmerArray,
};
// 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)
.setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
.setHTML('<img src=\'' + marker.properties.image + '\' width=\'50\' height=\'50\' border-radius=\'50%\'>' + '<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
.addTo(map);
});
And here is the code embedded in each CMS item that adds a farmer's information to the farmerArray which is being read by Mapbox. Text in double-quotations "" is a placeholder for the dynamic information populated by the CMS.
var farmerArrayItem =
JSON.stringify({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: ["longitude", "latitude"]
},
properties: {
title: "name",
description: "text",
image: "imagepath"
}
});
farmerArray.push(farmerArrayItem);
It doesn't appear that you have tried using the Developer Tools to debug your code. That's definitely a skill you should pick up.
With the dev tools, you will quickly see that the value of marker at the critical point is a string:
So you just need to use JSON.parse:
geojson.features.forEach(function(markerString) {
const marker = JSON.parse(markerString);
// 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)

How can I add Mapbox vector tile layer from Geoserver to Mapbox?

I have published a shapefile as a vector tile on GeoServer according to this. Now, how can I add this layer to Mapbox?
I would be very pleased if you can help me.
I have been trying to get that to work and for a vector layer you must specify 'source-layer' attribute which is the name of a layer on your GeoServer (ie. 'states' if using topp workspace) here is a code example that eventually worked for me:
<script>
mapboxgl.accessToken =
'<YOUR MAPBOX TOKEN HERE>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-100, 40],
zoom: 12,
});
map.on('load', function () {
map.addSource('wms-test-source', {
type: 'vector',
// use the tiles option to specify a WMS tile source URL
// https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/
tiles: [
'http://<YOUR GEOSERVER ADDRESS>:8080/geoserver/gwc/service/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&LAYER=topp:states&STYLE=&TILEMATRIX=EPSG:900913:{z}&TILEMATRIXSET=EPSG:900913&FORMAT=application/vnd.mapbox-vector-tile&TILECOL={x}&TILEROW={y}',
],
'minZoom': 0,
'maxZoom': 14,
});
map.addLayer(
{
'id': 'wms-test-layer',
'type': 'fill',
'source': 'wms-test-source',
'source-layer': 'states',
'paint': { 'fill-color': '#00ffff' },
}
//'aeroway-line'
);
});
</script>
For more info go to GeoServer documentation at GeoServer - Mapbox Style Specification
The code provided at the link actually shows how to add the GeoServer layer to your Mapbox map. Assuming that you want to add the layer to your map with Mapbox GL JS (since your post is tagged with mapbox-gl-js, your code would look something like this:
mapboxgl.accessToken = /* YOUR MAPBOX ACCESS TOKEN HERE */;;
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v11', // stylesheet location
center: [-74.5, 40], // starting position [lng, lat]
zoom: 9 // starting zoom
});
// Add the GeoServer layers as a source to your map.
map.addSource(
"<source-name>": {
"type": "vector",
"tiles": [
"http://localhost:8080/geoserver/gwc/service/wmts?REQUEST=GetTile&SERVICE=WMTS
&VERSION=1.0.0&LAYER=<workspace>:<layer>&STYLE=&TILEMATRIX=EPSG:900913:{z}
&TILEMATRIXSET=EPSG:900913&FORMAT=application/vnd.mapbox-vector-tile
&TILECOL={x}&TILEROW={y}"
],
"minZoom": 0,
"maxZoom": 14
}
);
// Style the GeoServer source in order to display it visually on your map
map.addLayer({
'id': 'geoserver-layer',
'type': /* fill in based on options here: https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#type */,
'source': '<source-name>'
/* Add any additional properties, full details here: https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#type */
});
In short, the GeoServer documentation link provides the code for adding a source to your map, and then you should add a layer to style the source visually on your map.
I'd recommend taking a look at the many Mapbox GL JS examples to get a sense of how sources and layers can be added, styled, modified, etc.

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!

OpenLayers 3: White gaps between OSM map tiles

As of openlayers 3.11, raster reprojection is introduced. I used OSM as a background layer and it works perfectly on some projection, such as EPSG:25832. Now I need to work on another projection EPSG:2326 but it shows some white gaps between map tiles when zoomed into the map.
I created a jsfiddle for reference, can someone help? Thanks!
var myMap = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: [837814, 818872],
projection: 'EPSG:2326',
zoom: 19
})
});
https://jsfiddle.net/86Lu9nd7/
This is a bug in OpenLayers. See https://github.com/openlayers/ol3/issues/4681 for its status.