In mapbox how do I move a Feature to top (z-index wise)? - mapbox

I have a layer full of state border "Features". When a user clicks on a State, I want to move that state's Feature to the top of the stack (z-index wise).
export function drawStateBorders() {
$.getJSON('https://www.mapbox.com/mapbox-gl-js/assets/us_states.geojson').then((data) => {
this.stateGeoJSON = data;
this.map
.addSource('states', {
type: 'geojson',
data,
})
.addLayer({
id: 'state-borders',
type: 'line',
source: 'states',
paint: {
'line-color': [
'case', ['boolean', ['feature-state', 'selected'], false],
'#8d8b76',
'#bfe2ab',
],
'line-width': [
'case', ['boolean', ['feature-state', 'selected'], false],
6,
3,
],
},
});
});
}
When I select the state
export function stateSelected(state) {
const stateFeatures = this.map.queryRenderedFeatures({
layers: ['state-borders'],
filter: [
'==', 'STATE_NAME', state,
],
});
const features = this.stateGeoJSON.features;
const currentFeature = stateFeatures[0];
if (!currentFeature) {
return;
}
// same state
if (currentFeature.id === this.selectedStateId) return;
// move to front HERE ?????
// old selected state
if (this.selectedStateId) {
this.map.setFeatureState({
source: 'states',
id: this.selectedStateId,
}, {
selected: false,
});
}
this.selectedStateId = currentFeature.id;
this.map.setFeatureState({
source: 'states',
id: this.selectedStateId,
}, {
selected: true,
});
}
So far I've tried
features.splice(features.indexOf(currentFeature), 1);
features.push(currentFeature);
this.map.getSource('states').setData(this.stateGeoJSON);
This seems to do some really crazy stuff to the array (duplicating some states, removing others). No idea what's happening

Adding the state to another layer worked (thanks #AndrewHarvey for the advice).
In case anyone is interested here is my code
export function stateSelected(state) {
const features = this.stateGeoJSON.features;
const currentFeature = features.find(s => s.properties.NAME === state);
if (!currentFeature) {
return;
}
// removes active layer
this.removeLayersContaining('state-borders-active');
this.drawActiveStateLayer(currentFeature);
}
export function drawActiveStateLayer(feature) {
this.map
.addLayer({
id: 'state-borders-active',
type: 'line',
source: {
type: 'geojson',
data: feature
},
paint: {
'line-color': '#8d8b76',
'line-width': 6,
},
});
}
export function drawStateBorders() {
$.getJSON('states.json').then((data) => {
this.stateGeoJSON = data;
this.map
.addSource('states', {
type: 'geojson',
data,
})
.addLayer({
id: 'state-borders',
type: 'line',
source: 'states',
paint: {
'line-color': '#bfe2ab',
'line-width': 3,
},
});
});
Also this is the shapefile I'm using: http://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_500k.json

Related

How to have two mapbox raster layers with different opacities?

Im using Mapbox GL API, and I run into the issue that if I add 2 tile layers, that the opacity of the second layer in the paint object is ignored. Does anyone have any idea why this is? In the browser both tile layers have opacity 1.
let style1 = {
id: "source1-tile",
type: "raster",
source: "source1",
paint: {
"raster-opacity": 1.0
},
}
this.map.addLayer(style1);
let style2 = {
id: "source2-tile",
type: "raster",
source: "source2",
paint: {
"raster-opacity": 0.5
},
}
this.map.addLayer(style2);
// print result
console.log(this.map.getStyle().layers)
// this shows the following:
/*
[
{
id: "source1-tile"
paint: Object { "raster-opacity": 1 }
source: "source1"
type: "raster"
},
{
id: "source2-tile"
source: "source2"
type: "raster"
}
]
*/
Pay attention to add layers in map.load event. I've made this example based on mapbox-gl examples. Easily You could add more raster layers with different opacity.
mapboxgl.accessToken = 'pk.eyJ1IjoibHN0aXoiLCJhIjoiY2s5dGtnNTZ2MWVybzNobjEyam0yd2E3MyJ9.6dCvGbS93SKGMbOqZA4Qag';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: [-87.62, 41.86],
zoom: 9
});
map.on('load', () => {
map.addSource('chicago', {
'type': 'raster',
'url': 'mapbox://mapbox.u8yyzaor'
});
map.addLayer({
'id': 'chicago',
'source': 'chicago',
'type': 'raster'
});
map.setPaintProperty(
'chicago',
'raster-opacity',
0.5
);
});

How to use react-map-gl to draw line between two point

I am trying to draw a line between two points using react-map-gl library. I can not find example from the official document, So I am trying to reproduce same behavior from following code snippet which use Mapbox library
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-122.486052, 37.830348],
zoom: 15
});
map.on('load', function() {
map.addSource('route', {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'LineString',
'coordinates': [
[-122.483696, 37.833818],
[-122.493782, 37.833683]
]
}
}
});
map.addLayer({
'id': 'route',
'type': 'line',
'source': 'route',
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': '#888',
'line-width': 8
}
});
});
Here is the sandbox, I do not see any errors on the console but the line is not displayed:
https://codesandbox.io/s/draw-line-between-two-point-v0mbc?file=/src/index.js:214-226
The code in the sandbox actually works (for me anyway), but is misleading because the line drawn is nowhere near the viewport.
A couple of things to note are that coordinates are an array given in [long, lat] which may not be what most people would assume. For example, if you cut and paste [lat,long] from google maps for San Fransisco, you get [37.77909036739809, -122.41510269913951]. Then you'll have to reverse those and put them in:
const dataOne = {
type: "Feature",
properties: {},
geometry: {
type: "LineString",
coordinates: [
[-122.41510269913951, 37.77909036739809],
[39.5423, -77.0564]
]
}
};
Also, the sample code has some cruft in it. Edit the variable dataOne not the other unused place.
Now you'll see a line from San Fransisco to some random spot in the middle of Antarctica that was really easy to miss.
Just in case the link goes bad, the full code is:
import React, { Component } from "react";
import { render } from "react-dom";
import ReactMapGL, { Source, Layer } from "react-map-gl";
class App extends Component {
constructor(props) {
super(props);
this.state = {
viewport: {
latitude: 38.63738602787579,
longitude: -121.23576311149986,
zoom: 6.8,
bearing: 0,
pitch: 0,
dragPan: true,
width: 600,
height: 600
}
};
}
render() {
const { viewport } = this.state;
const MAPBOX_TOKEN =
"pk.eyJ1Ijoic21peWFrYXdhIiwiYSI6ImNqcGM0d3U4bTB6dWwzcW04ZHRsbHl0ZWoifQ.X9cvdajtPbs9JDMG-CMDsA";
const dataOne = {
type: "Feature",
properties: {},
geometry: {
type: "LineString",
coordinates: [
[-122.41510269913951, 37.77909036739809],
[39.5423, -77.0564]
]
}
};
return (
<ReactMapGL
{...viewport}
mapboxApiAccessToken={MAPBOX_TOKEN}
onViewportChange={(newViewport) => {
this.setState({ viewport: newViewport });
}}
>
<Source id="polylineLayer" type="geojson" data={dataOne}>
<Layer
id="lineLayer"
type="line"
source="my-data"
layout={{
"line-join": "round",
"line-cap": "round"
}}
paint={{
"line-color": "rgba(3, 170, 238, 0.5)",
"line-width": 5
}}
/>
</Source>
</ReactMapGL>
);
}
}
render(<App />, document.getElementById("root"));

Adding multiple sources and layers with .each?

I try to simplify my codebase for an ongoing project. I render different lines from different sources. Adding the source and layer one by one works as expected. But if I put this in an object it won't work. I even have no errors in the console. Now I am stuck at the following code
var trip_entries = {
t2: {
trip_id: 'trip-entry-2',
trip_geojson: '[[-0.15591514, 51.51830379],[-0.07571203, 51.51424049],[-0.08533793, 51.50438536],[-0.085793, 51.5036],[-0.084793, 51.503336],[-0.089793, 51.505336]]'
},
t3: {
trip_id: 'trip-entry-3',
trip_geojson: '[[-0.15514, 51.518],[-0.075703, 51.515],[-0.085793, 51.50],[-0.0793, 51.506],[-0.08473, 51.50336],[-0.0893, 51.536]]'
},
};
// Set route
$.each(trip_entries,function(key,value){
// Add sources
map.addSource(value.trip_id,{
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': value.trip_geojson
}
},
],
},
});
// Add layers
map.addLayer({
'id': value.trip_id,
'type': 'line',
'source': value.trip_id,
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': 'rgb(160,160,160)',
'line-width': 6,
}
});
});
You are passing the geoJSON as a string, rather than an array of coordinates. You should remove the ' ' on both of your geoJSONs to get the code to run. See below:
mapboxgl.accessToken =
"pk.eyJ1IjoicGxtYXBib3giLCJhIjoiY2s3MHkzZ3VnMDFlbDNmbzNiajN5dm9lOCJ9.nbbtDF54HIXo0mCiekVxng";
var map = new mapboxgl.Map({
container: "map", // container id
style: "mapbox://styles/mapbox/streets-v11", // stylesheet location
center: [-0.084793, 51.503336], // starting position [lng, lat]
zoom: 11 // starting zoom
});
var trip_entries = {
t2: {
trip_id: "trip-entry-2",
trip_geojson: [
[-0.15591514, 51.51830379],
[-0.07571203, 51.51424049],
[-0.08533793, 51.50438536],
[-0.085793, 51.5036],
[-0.084793, 51.503336],
[-0.089793, 51.505336]
]
},
t3: {
trip_id: "trip-entry-3",
trip_geojson: [
[-0.15514, 51.518],
[-0.075703, 51.515],
[-0.085793, 51.5],
[-0.0793, 51.506],
[-0.08473, 51.50336],
[-0.0893, 51.536]
]
}
};
map.on("load", function () {
// Set route
$.each(trip_entries, function (key, value) {
// Add sources
map.addSource(value.trip_id, {
type: "geojson",
data: {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
type: "LineString",
coordinates: value.trip_geojson
}
}
]
}
});
// Add layers
map.addLayer({
id: value.trip_id,
type: "line",
source: value.trip_id,
layout: {
"line-join": "round",
"line-cap": "round"
},
paint: {
"line-color": "rgb(160,160,160)",
"line-width": 6
}
});
});
});
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.css" rel="stylesheet" />
<div id="map"></div>

How to change icon-size in mapbox gl on click?

I want to change the icon-size on map click based on the turf-nearest. How do i accomplish this? nearestBuilding.properties['icon-size'] = 0.2; does not work.
var retail = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: {
title: 'TEST',
description: 'TEST'
},
geometry: {
type: 'Point',
coordinates: [121.051779, 14.550224]
}
},
{
type: 'Feature',
properties: {
title: 'TEST',
description: 'TEST'
},
geometry: {
type: 'Point',
coordinates: [121.04568958282472, 14.552170837008527]
}
}
]
};
map.on('load', function() {
map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Wiki_Loves_Earth_map_marker.svg/600px-Wiki_Loves_Earth_map_marker.svg.png', function(error, image) {
if (error) throw error;
map.addImage('marker', image);
map.addLayer({
id: 'retail',
type: 'symbol',
source: {
type: 'geojson',
data: retail
},
layout: {
'icon-image': 'marker',
'icon-size': 0.1
},
paint: { }
});
});
});
var marker = null;
map.on('click', function(e){
if(marker != null) {
marker.remove();
}
var currentLocation = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [e.lngLat.lng, e.lngLat.lat]
}
};
var el = document.createElement('div');
el.className = 'currLocMarker';
marker = new mapboxgl.Marker(el, { offset: [-50 / 2, -50 / 2] })
.setLngLat(currentLocation.geometry.coordinates)
.addTo(map);
var currentLocation = turf.point([e.lngLat.lng, e.lngLat.lat]);
var nearestBuilding = turf.nearest(currentLocation, retail);
var distance = turf.distance(currentLocation, nearestBuilding);
if (distance <= 0.5) {
nearestBuilding.properties['icon-size'] = 0.2;
}
});
Since icon-size supports data-driven styling(https://www.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-size), have you tried doing that, with an identity function from the property on each feature? You would configure this inside the layout, instead just hard-coding 0.1.
More docs on data-driven styling is here - https://www.mapbox.com/mapbox-gl-js/style-spec/#function-type

Submit all of grid rows with Extjs form submit

I have a grid panel in a form. Any row of the grid panel have a filefield. I want to send any row (name field and filename field) to server.
Model:
Ext.define('FM.model.DefineCode', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'filename', type: 'string'}
],
validations: [
{type: 'presence', field: 'id'},
{type: 'presence', field: 'name'},
{type: 'presence', field: 'filename'}
]
});
Store:
Ext.define('FM.store.DefineCode', {
extend: 'Ext.data.Store',
model: 'FM.model.DefineCode',
autoLoad: true,
data: []
});
View:
Ext.define('FM.view.map.DefineCode', {
extend: 'Ext.window.Window',
title: 'Define Code',
alias: 'widget.mmDefineCode',
width: 600,
modal: true,
items: [{
xtype: 'form',
items: [{
xtype: 'gridpanel',
title: 'myGrid',
store: 'DefineCode',
columns: [
{
text: 'Id',
xtype: 'rownumberer',
width: 20
}, {
text: 'Name',
dataIndex: 'name',
flex: 1,
editor:{
xtype: 'textfield'
}
}, {
text: 'File',
dataIndex: 'filename',
width: 200,
editor:{
xtype: 'filefield',
emptyText: 'Select your Icon',
name: 'photo-path',
buttonText: '',
flex: 1,
buttonConfig: {
iconCls: 'icon-upload-18x18'
},
listeners: {
change: function(e, ee, eee) {
var grid = this.up('grid');
var store = grid.getStore();
var newStore = Ext.create('FM.store.DefineCode',{});
store.insert(store.data.items.length, newStore);
}
}
},
}, {
text: '',
width: 40
}
],
height: 200,
width: 600,
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1
})
]}
],
}],
buttons: [{text: 'OK', action: 'OK'}],
initComponent: function() {
var me = this;
Ext.apply(me, {});
me.callParent(arguments);
}
});
Controller:
...
form.submit({
url: 'icon/create',
});
When I submit form, only last row is sending to server.
Where is problem?
Why you using this ?
var newStore = Ext.create('FM.store.Path', {});
store.insert(store.data.items.length, newStore);
try using rowEditing to edit/submit 1 row data :
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
clicksToEdit: 2,
clicksToMoveEditor: 1,
listeners: {
'validateedit': function(editor, e) {},
'afteredit': function(editor, e) {
var me = this;
var jsonData = Ext.encode(e.record.data);
Ext.Ajax.request({
method: 'POST',
url: 'your_url/save',
params: {data: jsonData},
success: function(response){
e.store.reload({
callback: function(){
var newRecordIndex = e.store.findBy(
function(record, filename) {
if (record.get('filename') === e.record.data.filename) {
return true;
}
return false;
}
);
me.grid.getSelectionModel().select(newRecordIndex);
}
});
}
});
return true;
}
}
});
and place it to your plugin.
I don't try it first, but may be this will help you a little.
AND this is for your controller to add a record from your grid, you need a button to trigger this function.
createRecord: function() {
var model = Ext.ModelMgr.getModel('FM.model.DefineCode');
var r = Ext.ModelManager.create({
id: '',
name: '',
filename: ''
}, model);
this.getYourgrid().getStore().insert(0, r);
this.getYourgrid().rowEditing.startEdit(0, 0);
}
check this for your need, this is look a like. You need to specify the content-type.
And for your java need, please read this method to upload a file.