react-mapbox-gl markers are not displayed correctly - mapbox-gl-js

I have a site with mapbox, the map itself works fine, but I can't add markers to it.
I copied the code from one source on which everything works, but when I added it to my project, the markers shifted from the correct coordinates on the map and got even more shifted when approaching.
here's my code
import React, { useState } from "react";
import ReactDOM from "react-dom";
import ReactMapboxGl, { Layer, Marker } from "react-mapbox-gl";
import { observer } from "mobx-react-lite";
import state from "../../state/state";
const Map = ReactMapboxGl({
accessToken:
"pk.eyJ1IjoibmFnaHQiLCJhIjoiY2wyYTJrazZxMDFlbzNpbnp0eTNnOG44aCJ9.i3nyiAJBTDyWviIWhsX-Zg",
});
const IndexMap = observer(({ coordinats }) => {
return (
<div style={{ height: "100vh", width: "100%", overflow: "hidden" }}>
<Map
style="mapbox://styles/mapbox/streets-v9" // eslint-disable-line
containerStyle={{
height: "100%",
width: "100%",
}}
center={{
lat: 51.5285582,
lng: -0.2416815,
}}
zoom={[12]}
>
<Marker coordinates={[-0.2416815, 51.5285582]} anchor="bottom">
<h1>marker</h1>
</Marker>
</Map>
</div>
);
});
export default IndexMap;
I think there are not enough styles for the map to set them in the right location.

I don't know what the problem was. I just moved the project to the folder with the working file. The link to the folder with the working file -https://codesandbox.io/embed/pwly8?codemirror=1

Related

Displaying TIFF data on React-Leaflet Map

I have basic javascript code that uses a simple Leaflet map; I have TIFF files that I parse through, and then I can display these on the map though Layer Control, in a simple index.html file. I can't figure out how to show the TIFF data in react-leaflet though. I can parse the data properly, but react-leaflet only seems to take PNG or PNG url's, and I can't find any documentation or anything that shows how to show TIFF files. I'm sure I'm missing something simple, but it's super frustrating :(
This is my code with react, and react-leaflet. It's working + parsing the TIFF data, I just don't know how to add the data to the layerscontrol baselayer TileLayer...
import React, { useMemo, useState } from "react";
import {
TileLayer,
Marker,
Popup,
MapContainer,
LayersControl,
LayerGroup,
FeatureGroup,
Circle,
useMap,
} from 'react-leaflet';
import chroma from 'chroma-js';
import parseGeoraster from 'georaster';
import GeoRasterLayer from 'georaster-layer-for-leaflet';
import AddLocate from "../components/AddLocate";
import { Helmet } from 'react-helmet';
import sample from '../data/tmin.tiff';
const MapBody = () => {
const center = [0, 0];
let tmin_layer = '';
fetch(sample)
.then(response => response.arrayBuffer())
.then(arrayBuffer => {
parseGeoraster(arrayBuffer).then(georaster => {
const min = georaster.mins[0];
const max = georaster.maxs[0];
const range = georaster.ranges[0];
const scale = chroma.scale('Spectral').domain([1, 0]);
tmin_layer = new GeoRasterLayer({
georaster: georaster,
opacity: 0.7,
pixelValuesToColorFn: function (pixelValues) {
var pixelValue = pixelValues[0];
if (pixelValue === 0) return null;
const scaledPixelValue = (pixelValue - min) / range;
const color = scale(scaledPixelValue).hex();
return color;
},
resolution: 256
});
console.log("layer:", tmin_layer);
})
})
return (
<>
<Helmet>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
/>
</Helmet>
<MapContainer className="map" center={center} zoom={2} scrollWheelZoom={false} doubleClickZoom={true}>
<TileLayer
className="tile"
attribution='&copy OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
//prevents map duplicating
noWrap={true} />
<LayersControl position="topright">
<LayersControl.BaseLayer name="TOPO TESTING">
<TileLayer className="tiles" url="https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png"/>
</LayersControl.BaseLayer>
<LayersControl.BaseLayer name="TIFF TEST">
<TileLayer className="tiffy" url={tmin_layer}/>
</LayersControl.BaseLayer>
</LayersControl>
<AddLocate/>
</MapContainer>
</>
)
}
export default MapBody;

how to use react-leaflet with preact

I am trying to use react-leaflet with preact with little success. I do actually render the map but it is not rendered together, as in the tiles are scattered over the page and outside the containing element.
I have read all (some) related questions on SO that say you need to either import the css file from leaflet (import "leaflet/dist/leaflet.css") or include a css file with a class for .leaflet-container. I have tried both and it is still not working.
I followed the instruction on the react leaflet website to install the necessary dependencies.
My project uses rollup so I added the following to my rollup config:
alias({
entries: [
{ find: 'react', replacement: 'preact/compat' },
{ find: 'react-dom', replacement: 'preact/compat' },
{ find: 'react-dom/test-utils', replacement: 'preact/test-utils' },
{ find: 'react/jsx-runtime', replacement: 'preact/jsx-runtime' }
]
}),
And my component looks like this:
import { h } from 'preact';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import { Icon } from "leaflet";
import "../../styles/leaflet.css";
const Map = (): JSX.Element => {
type LatLngTuple = [number, number];
const position: LatLngTuple = [51.505, -0.09];
return (
<MapContainer center={position} zoom={13} scrollWheelZoom={false} >
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
);
};
export default Map;

MUI V5 - MakeStyles style gets overwritten

I just updated to 5.0.0-alpha.25 (coming from 5.0.0-alpha.10) and now makeStyles is not working. I could not find anything in the breaking changes related to it so I wonder if it is a bug. When inspecting an element the makeStyles css rule is overwritten by a strange called css rule which seems to be the default values.
Here is an image which shows the rules in the inspector
Did anyone face the same issue or am I overseeing a change in the makeStyles usage.
const useStyles = makeStyles((theme) => ({
root: {
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
paddingLeft: theme.spacing(2),
paddingRight: theme.spacing(2),
display: 'contents'
},
row: {
backgroundColor: "red"
}
}));
/* ... */
const classes = useStyles()
/* ... */
<Grid container spacing={1} className={classes.root} alignItems="flex-start" justifyContent="center">
I had the same problem. You need to wrap your entire application in StyledEngineProvider component. I've done this in index.js file. Restart you local server by npm start nad works perfectly
Here's example
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import StyledEngineProvider from '#mui/material/StyledEngineProvider'
ReactDOM.render( <StyledEngineProvider injectFirst> <App /> </StyledEngineProvider>,
document.getElementById('root')
);

I was trying out Uber's deck.gl by adding the component to my react app. But nothing appears. Any help would be appreciated

I was trying out Uber's deck.gl by adding the component to my react app. But nothing appears.
I believe it could be related to mapbox. It appeared once but that was it.
I set the width, height, etc. But nothing works.
This is basic example in their site.
Deck Gl with React
Here is my code. deckgl.component.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import { StaticMap } from 'react-map-gl';
import DeckGL, { LineLayer, ScatterplotLayer } from 'deck.gl';
const MAPBOX_ACCESS_TOKEN = '<MAPBOX_TOKEN>';
// Viewport settings
const INITIAL_VIEW_STATE = {
latitude: 37.785164,
longitude: -122.41669,
zoom: 16,
bearing: -20,
pitch: 60
};
class DeckGlComponent extends Component {
render() {
return (
<DeckGL initialViewState={INITIAL_VIEW_STATE} controller={true} width="100%" height="100%">
<StaticMap mapboxApiAccessToken={MAPBOX_ACCESS_TOKEN} />
<LineLayer
data={[{ sourcePosition: [-122.41669, 37.7883], targetPosition: [-122.41669, 37.781] }]}
getStrokeWidth={5}
/>
<ScatterplotLayer
data={[{ position: [-122.41669, 37.79] }]}
radiusScale={100}
getFillColor={[0, 0, 255]}
/>
</DeckGL>
);
}
}
export default DeckGlComponent;
and index.js
import React from 'react';
import { render } from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
import DeckGlComponent from './deckgl.component';
render(
<DeckGlComponent />,
document.getElementById('root')
);
serviceWorker.unregister();
It's absolutely basic. But nothing turns up. I created a new mapbox token just to be sure and still nothing.
According to your description (since there's not too much information), and mapbox token is active as you said, I suspect if you create a HTML file contains root element, like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#root {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="root"></div>
</body>
</html>
This file is required when you calling these codes:
render(
<DeckGlComponent />,
document.getElementById('root')
);
You can put your code on codepen or some online editors, so that we can help you more specifically.
Besides, I recommend you read codes in this folder https://github.com/uber/deck.gl/tree/master/examples/get-started rather than the codes in documents. Sometimes, codes in documents is for explaining concepts, and not ready for running.

Make react-leaflet map component resize itself to fit available space

Setting the width of the Map component works, but height seems to only respond to an absolute size in pixels.
Is it possible to make the map control automatically consume available space inside the parent element?
I was able to create a component that passed in a component state value for the height of the map. I created a helper function that would resize the height to make it all responsive.
...
export default class MapContainer extends React.Component {
updateDimensions() {
const height = window.innerWidth >= 992 ? window.innerHeight : 400
this.setState({ height: height })
}
componentWillMount() {
this.updateDimensions()
}
componentDidMount() {
window.addEventListener("resize", this.updateDimensions.bind(this))
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions.bind(this))
}
...
render() {
...
return (
<div class="map-container" style={{ height: this.state.height }}>
<Map>
...
</Map>
</div>
)
}
}
I solved this by using the react-container-dimensions component, which passes width/height as props to its child:
<div className="div that can resize""
ContainerDimensions>
<MyMapContainer/>
</ContainerDimensions>
</div>
...
style.width = Math.floor(this.props.width);
return (
<Map style={style}
Setting min-height & height to 100% on MapContainer worked form me:
<div style={{ height: "175px" }}><MapContainer style={{ height: "100%", minHeight: "100%" }} ...</div>
I solved this by setting the height of leaflet-container to 100% in my .css file.
.leaflet-container {
height: 100%;
}
With my Map component looking like this:
const Map = () => {
return (
<MapContainer center={[51.4381, 5.4752]} zoom={10} >
<TileLayer
maxZoom='20'
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
)
}
export default Map;