I'm setting up a map to find the coords of a person and then put that location on the map. But for some reason, the coords aren't being shown on the map. I console.log to make sure the state variables(where the coords are being stored) were emitting the right coords and they are. I don't know why the map won't change to them though.
My code:
import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import Constants from "expo-constants";
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";
import { render } from "react-dom";
import "leaflet/dist/leaflet.css";
export default class App extends React.Component {
constructor() {
super();
this.state = {
ready: false,
where: { lat: '', lng: '' },
error: null,
};
}
componentDidMount() {
let geoOptions = {
enableHighAccuracy: true,
timeOut: 20000,
maximumAge: 60 * 60 * 24,
};
this.setState({ ready: false, error: null });
navigator.geolocation.getCurrentPosition(
this.geoSuccess,
this.geoFailure,
geoOptions
);
}
geoSuccess = (position) => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
console.log(this.state.where?.lng);
console.log(this.state.where?.lat);
this.setState({
ready: true,
where: { lat: position.coords.latitude, lng: position.coords.longitude
},
});
console.log(this.state.where?.lng);
console.log(this.state.where?.lat);
};
geoFailure = (err) => {
this.setState({ error: err.message });
console.log(this.state.error);
};
render() {
const position = [this.state.where?.lat, this.state.where?.lng];
return (
<>
{(this.state.where != null || this.state.where != undefined) &&
<MapContainer
style={{ height: "100%", width: "100%" }}
center={position}
zoom="30"
scrollWheelZoom={true}
>
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
}
</>
);
}
}
From the official docs
Except for its children, MapContainer props are immutable: changing
them after they have been set a first time will have no effect on the
Map instance or its container.
Use a child component that will change your map view upon position change
function ChangeMapView({ coords }) {
const map = useMap();
map.setView(coords, map.getZoom());
return null;
}
Use it like this:
<MapContainer
style={{ height: "100vh", width: "100%" }}
center={position}
zoom="30"
scrollWheelZoom={true}
>
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<ChangeMapView coords={position} />
</MapContainer>
Demo
Related
I want to move the position in the Basemap Gallery Leaflet to the top near the Leaflet zoom on the Map but am confused about how to move the coding, here it is:
Basemap Gallery Brochure wants to move up and near Zoom.
Sample image: Images
Example of desired Basemap Gallery position:
Example of Basemap Gallery position
Here is my code and what I need to change in my code:
import { React, useState, useEffect } from 'react'
import {
LayersControl,
MapContainer,
TileLayer,
Marker,
Popup,
useMapEvents,
} from 'react-leaflet'
import List from '../Component/List'
import L from 'leaflet'
import SearchControl from './SearchControl'
const { BaseLayer } = LayersControl
function LocationMarker() {
const [position, setPosition] = useState(null)
const map = useMapEvents({
locationfound(e) {
setPosition(e.latlng)
map.flyTo(e.latlng, map.getZoom())
},
})
return position === null ? null : (
<Marker position={position}>
<Popup>Location Me</Popup>
</Marker>
)
}
function MyLocationMe() {
const [map, setMap] = useState(null)
const [position, setPosition] = useState(null)
useEffect(() => {
if (!map) return
L.easyButton('fa-map-marker', () => {
map.locate().on('locationfound', function (e) {
setPosition(e.latlng)
map.flyTo(e.latlng, map.getZoom())
})
}).addTo(map)
}, [map])
return (
<div className="flex ml-auto">
<List />
<div className="w-4/5">
<MapContainer
center={{ lat: 51.505, lng: -0.09 }}
zoom={20}
style={{ height: '100vh' }}
whenCreated={setMap}
>
<SearchControl className="MarkerIcon" position="topright" />
<LayersControl position="topleft">
<BaseLayer checked name="OpenStreetMap">
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png "
/>
</BaseLayer>
</LayersControl>
<LocationMarker />
</MapContainer>
</div>
</div>
)
}
export default MyLocationMe
The easiest way to do that is to change the left css property of the relevant css class by making position absolute
Add this to your styles.css
.leaflet-control-layers.leaflet-control {
position: absolute;
left: 50px;
}
Demo
I want to move the position on the BasemapGallery Leaflet and GeoSearch Leaflet on the Map but for confusion how to move in coding, here is:
The BasemapGallery leaflet wants to move to the right, and
The GeoSearch leaflet wants to move to the left.
Sample image:
Image
Here is my code and what I need to change in my code:
import { React, useState, useEffect } from 'react'
import {
LayersControl,
MapContainer,
TileLayer,
Marker,
Popup,
useMapEvents,
} from 'react-leaflet'
import List from '../Component/List'
import L from 'leaflet'
import SearchControl from './SearchControl'
const { BaseLayer } = LayersControl
function LocationMarker() {
const [position, setPosition] = useState(null)
const map = useMapEvents({
locationfound(e) {
setPosition(e.latlng)
map.flyTo(e.latlng, map.getZoom())
},
})
return position === null ? null : (
<Marker position={position}>
<Popup>Location Me</Popup>
</Marker>
)
}
function MyLocationMe() {
const [map, setMap] = useState(null)
const [position, setPosition] = useState(null)
useEffect(() => {
if (!map) return
L.easyButton('fa-map-marker', () => {
map.locate().on('locationfound', function (e) {
setPosition(e.latlng)
map.flyTo(e.latlng, map.getZoom())
})
}).addTo(map)
}, [map])
return (
<div className="flex ml-auto">
<List />
<div className="w-4/5">
<MapContainer
center={{ lat: 51.505, lng: -0.09 }}
zoom={20}
style={{ height: '100vh' }}
whenCreated={setMap}
>
<SearchControl className="MarkerIcon" />
<LayersControl>
<BaseLayer checked name="OpenStreetMap">
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png "
/>
</BaseLayer>
</LayersControl>
<LocationMarker />
</MapContainer>
</div>
</div>
)
}
export default MyLocationMe
There should be a position attribute for the controls:
<SearchControl className="MarkerIcon" position="topright" />
and
<LayersControl position="topleft">
<BaseLayer checked name="OpenStreetMap">
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png "
/>
</BaseLayer>
</LayersControl>
I'm trying to get coordinates of where the mouse clicks on the map but .locate() only returns the center coordinates of the map.
Is there a way?
ps. I am not using class based react.
Thanks
<MapContainer
center={[ 33.8735578, 35.86379]}
zoom={9}
scrollWheelZoom={true}
>
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
you can get coordinates of mouse click by useMapEvents hook.
try this one.
const MapEvents = () => {
useMapEvents({
click(e) {
// setState your coords here
// coords exist in "e.latlng.lat" and "e.latlng.lng"
console.log(e.latlng.lat);
console.log(e.latlng.lng);
},
});
return false;
}
return (
<MapContainer
center={[ 33.8735578, 35.86379]}
zoom={9}
scrollWheelZoom={true}
>
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MapEvents />
</MapContainer>
)
Question and where is your code? You are not new to this site so you should know to show what you have done so far.
Okay, I will be gracious today ;)
I don't want to cut and clean the code, so I paste as is.
import { useEffect } from 'react';
import { MapContainer, useMap, TileLayer, } from 'react-leaflet';
import L from 'leaflet';
import tileLayer from '../util/tileLayer';
const center = [52.22977, 21.01178];
const GetCoordinates = () => {
const map = useMap();
useEffect(() => {
if (!map) return;
const info = L.DomUtil.create('div', 'legend');
const positon = L.Control.extend({
options: {
position: 'bottomleft'
},
onAdd: function () {
info.textContent = 'Click on map';
return info;
}
})
map.on('click', (e) => {
info.textContent = e.latlng;
})
map.addControl(new positon());
}, [map])
return null
}
const MapWrapper = () => {
return (
<MapContainer center={center} zoom={18} scrollWheelZoom={false}>
<TileLayer {...tileLayer} />
<GetCoordinates />
</MapContainer>
)
}
export default MapWrapper;
I'm using Google Maps API to show places on a map. However, every time I drag the location on my map, I get the following errors:
Here is my Google map, using Google Maps API, recompose and react-google-maps. It works, but is giving errors.
/*global google*/
import React from "react"
import { compose, withProps, withHandlers, withState } from "recompose"
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps"
const MyMapComponent = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withScriptjs,
withGoogleMap,
withState('places', 'updatePlaces', ''),
withHandlers(() => {
const refs = {
map: undefined,
}
return {
onMapMounted: () => ref => {
refs.map = ref
},
fetchPlaces: ({ updatePlaces }) => {
let places;
const bounds = refs.map.getBounds();
const service = new google.maps.places.PlacesService(refs.map.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED);
const request = {
bounds: bounds,
type: ['hotel']
};
service.nearbySearch(request, (results, status) => {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log(results);
updatePlaces(results);
}
})
}
}
}),
)((props) => {
return (
<GoogleMap
onTilesLoaded={props.fetchPlaces}
ref={props.onMapMounted}
onBoundsChanged={props.fetchPlaces}
defaultZoom={8}
defaultCenter={{ lat: 51.508530, lng: -0.076132 }}
>
{props.places && props.places.map((place, i) =>
<Marker key={i} position={{ lat: place.geometry.location.lat(), lng: place.geometry.location.lng() }} />
)}
</GoogleMap>
)
})
export default class MyFancyComponent extends React.PureComponent {
render() {
return (
<MyMapComponent />
)
}
}
I tried looking for a solution at Github issues, Google and here at StackOverflow, but couldn't find a solution yet.
How could I fix the errors, when changing (dragging) the location on the map?
withHandlers expects fetchPlaces function to be a higher-order function, so modify:
fetchPlaces: ({ updatePlaces }) => {
//...
}
with
fetchPlaces: ({ updatePlaces }) => () => {
//...
}
I'm trying to build my own Zoom button with react-leaflet
I have the following code:
import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { Map, TileLayer } from 'react-leaflet';
import Control from 'react-leaflet-control';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ZoomIn from 'material-ui/svg-icons/action/zoom-in';
import ZoomOut from 'material-ui/svg-icons/action/zoom-out';
class LeafletMap extends React.Component {
constructor(props) {
super(props);
this.state = {
animate: true,
center: [
-34.989610443115,
-71.232476234436
],
zoom: 13,
zoomControl: false
};
}
render() {
return (
<div>
<Map
animate={this.state.animate}
center={this.state.center}
zoom={this.state.zoom}
zoomControl={this.state.zoomControl}
>
<TileLayer
url={'http://{s}.tile.osm.org/{z}/{x}/{y}.png'}
attribution={'© OpenStreetMap'}
/>
<Control position="topleft">
<MuiThemeProvider>
<div>
<div> </div>
<FloatingActionButton mini={true}>
<ZoomIn onClick={ () => alert('Zoom In') } />
</FloatingActionButton>
<div> </div>
<FloatingActionButton mini={true}>
<ZoomOut onClick={ () => alert('Zoom Out') }/>
</FloatingActionButton>
</div>
</MuiThemeProvider>
</Control>
</Map>
</div>
);
}
}
export default LeafletMap;
All this is displaying good way, but now I want to to put a funcion where I can able to do zoom in or out. I don't have an idea how to call leaflet's methods using react-leaflet library.
I've tried many ways to implement it but without success.
Do you have any idea how to implement it?
There are a few ways to handle map functions/actions.
Pass via props
Many options are available via the Map's props(bounds, center, zoom). This way allows you to hold the zoom in your one state/store, instead of in leaflet.
const React = window.React;
const {
Map,
TileLayer,
Marker,
Popup
} = window.ReactLeaflet;
class ZoomInState extends React.Component {
constructor() {
super();
this.state = {
lat: 51.505,
lng: -0.09,
zoom: 13,
};
this.zoomIn = () => this.setState({zoom: this.state.zoom+1})
this.zoomOut = () => this.setState({zoom: this.state.zoom-1})
}
render() {
const position = [this.state.lat, this.state.lng];
return ( < Map center = {
position
}
zoom = {
this.state.zoom
}
>
< TileLayer attribution = '© OpenStreetMap contributors'
url = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png' / >
< Marker position = {
position
} >
< Popup >
< span >
<button onClick={this.zoomOut}>
Zoom out
</button >
< button onClick = {this.zoomIn} >
Zoom in
< /button>
< /span>
</Popup >
< /Marker>
</Map >
);
}
}
export default ZoomInState
Get map via refs
This way will not hold the zoom level in your component. Often this is a good practice, because it keeps a single source of truth. You can always get the zoom with map.getZoom()
const React = window.React;
const { Map, TileLayer, Marker, Popup } = window.ReactLeaflet;
class MapByRef extends React.Component {
constructor() {
super();
this.state = {
lat: 51.505,
lng: -0.09,
zoom: 13,
};
}
bindMap(el) {
this.map = el.leafletElement;
}
zoomIn() {
this.map.zoomIn();
}
zoomOut() {
this.map.zoomOut();
}
render() {
const position = [this.state.lat, this.state.lng];
return (
<Map center={position} zoom={this.state.zoom} ref={::this.bindMap}>
<TileLayer
attribution='© OpenStreetMap contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
<Marker position={position}>
<Popup>
<span>
<button onClick={::this.zoomIn} >Zoom In</button>
<button onClick={::this.zoomIn} >Zoom Out</button>
</span>
</Popup>
</Marker>
</Map>
);
}
}
export default MapByRef
3. Get from Context
This way is nice if you want to make many child components that need to interact with the map. It also keeps leaflet as the single source of truth.
const React = window.React;
const { Map, TileLayer, Marker, Popup } = window.ReactLeaflet;
class CustomMarker {
zoomIn(){
this.context.map.zoomIn()
}
zoomOut(){
this.context.map.zoomOut()
}
render() {
return (
<Marker position={position}>
<Popup>
<button onCLick={::this.zoomIn}>Zoom In</button>
<button onCLick={::this.zoomOut}>Zoom In</button>
</Popup>
</Marker>
)
}
}
export CustomMarker
class MapWithCustomChildren extends React.Component {
constructor() {
super();
this.state = {
lat: 51.505,
lng: -0.09,
zoom: 13,
};
}
render() {
const position = [this.state.lat, this.state.lng];
return (
<Map center={position} zoom={this.state.zoom}>
<TileLayer
attribution='© OpenStreetMap contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
<CustomMarker />
</Map>
);
}
}
export default MapWithCustomChildren