How to add onClick to the map `leaflet` - javascript

I'm using Leaflet i want to show an alert that shows latlng of the clicked location
I followed document steps in here https://leafletjs.com/examples/quick-start/
I've tried this
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
function onMapClick(e) { //THE FUNCTION
alert("You clicked the map at " + e.latlng);
}
mymap.on('click', onMapClick);
and at <MapContainer> i defined it like
<MapContainer id="mapid" onClick={onMapClick}/>
but it shows nothing
here is the whole code
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'
import React, { Component } from 'react';
import L from 'leaflet'
class UserMap extends Component {
render() {
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
function onMapClick(e) {
alert("You clicked the map at " + e.latlng);
}
mymap.on('click', onMapClick);
return (
<div
id="mapid" style={{ height: '100%', width: '100%' }}>
<MapContainer
id="mapid"
center={[30.794900, 50.564580]}
zoom={13}
zoomOffset={1}
boxZoom={false}
scrollWheelZoom={true}
style={{ height: '500px', width: '100%' }}>
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
position={[30.794900, 50.564580]}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer></div>
);
}
}
export default UserMap;

onClick is not working anymore, instead you should use the useMapEvents hook (https://react-leaflet.js.org/docs/api-map/#usemapevents).
Basically, you have to create a component with the useMapEvents hook which will listen to the click and call this component in your MapContainer.
Add the following code inside your MapContainer to fix your issue:
function MyComponent() {
useMapEvents({
click(e){
alert(e.latlng)
}
})
}

Related

Set view to current location by clicking button

I have a project using React, react-leaflet and Framework 7. In one component I have a Fab-Button from Framework 7 and a Map from react-leaflet. My Map.jsx component looks like this:
import React, { useState } from "react";
import { MapContainer, TileLayer, useMapEvents, Marker, Popup } from "react-leaflet";
import "../css/leaflet.css";
import "../css/app.css";
import {Fab, Icon, PageContent} from "framework7-react";
export default function Map(){
function LocationMarker() {
const [position, setPosition] = useState(null)
const map = useMapEvents({
click() {
map.locate()
},
locationfound(e) {
setPosition(e.latlng)
map.flyTo(e.latlng, map.getZoom())
},
locationerror(e) {
alert("Unfortunately, we could not find your location")
}
})
return position === null ? null : (
<Marker position={position}>
<Popup>You are here</Popup>
</Marker>
)
}
function fabGoToCurrentPosition() {
//probably something like this:
map.locate()
}
return (
<>
<Fab position="right-bottom" slot="fixed" id="fab-button" onClick={() => {
fabGoToCurrentPosition()
}}>
<Icon f7="placemark_fill" ios="f7:placemark_fill" aurora="f7:placemark_fill"></Icon>
</Fab>
<PageContent className='page-content-map'>
<MapContainer center={[51.505, -0.09]} zoom={13} scrollWheelZoom={true} id="map">
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<LocationMarker/>
</MapContainer>
</PageContent>
</>
);
}
The function "LocationMarker" is from a react-leaflet tutorial and sets the position of the Map to the current location of the user if the Map is clicked. My aim is that the position is set if the user clicks the Fab-Button instead of the Map.

How to create BasemapGallery in React-Leaflet - ReactJS?

I'd like to ask if I'm using the map from React Leaflet (https://react-leaflet.js.org/) but how do I add the Base Map Gallery button to the map? like this example Basemap Gallery button on the image that I marked with red arrow and do I need to change or delete any of my code?
Example view of BasemapGallery but map from React-Leaflet - ReactJS:
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
Example view of BasemapGallery but map from React-Leaflet - ReactJS:
Images

Basemap Gallery in map from React Leaflet

I'd like to ask if I'm using the map from React Leaflet (https://react-leaflet.js.org/) but how do I add the Base Map Gallery button to the map? like this example Basemap Gallery button on the image that I marked with red arrow.
And pictures in the link:
Example of an arrow Basemap Gallery
An example on my map where I want to add Basemap Gallery
And how to show the Basemap Gallery button, where do you save it from my coding?
import { React, useState, useEffect } from 'react'
import {
LayersControl,
MapContainer,
TileLayer,
Marker,
Popup,
useMapEvents,
} from 'react-leaflet'
import L from 'leaflet'
import 'leaflet-easybutton/src/easy-button'
import 'leaflet-easybutton/src/easy-button.css'
import 'font-awesome/css/font-awesome.min.css'
const { BaseLayer } = LayersControl;
export default function MyMaps() {
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">
<div className="w-4/5">
<MapContainer
center={[51.505, -0.09]}
zoom={20}
style={{ height: "100vh" }}
whenCreated={setMap}
>
<LayersControl>
<BaseLayer checked name="OpenStreetMap">
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png "
/>
</BaseLayer>
</LayersControl>
</MapContainer>
</div>
</div>
);
}

react-leaflet get current zoom boundaries

I currently have this map
import React, { useEffect } from "react";
import "./App.css";
import { MapContainer, TileLayer, Marker } from "react-leaflet";
function App() {
useEffect(() => {
console.log("first run");
}, []);
return (
<div className="App">
<div id="mapid">
<MapContainer
style={{ height: "100vh", width: "100vw" }}
center={[51.505, -0.09]}
zoom={13}
scrollWheelZoom={true}
>
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[51.505, -0.09]}></Marker>
<Marker position={[51.490114, -0.09066]}></Marker>
</MapContainer>
</div>
</div>
);
}
export default App;
And i somehow need to find the latitude min, latitude max, longitude min, longitude max
But i cannot find how to do it with hooks / useeffect
After taking the map reference, when the component mounts, you can get the map bounds using map.getBounds(). It contains the current or the updated coordinates of southWest, southEast, northWest, northEast etc.
useEffect(() => {
if (!map) return;
console.log(map.getBounds());
}, [map]);
and if you want to take the new ones after you zoom in or out you can add a zoomend event
useEffect(() => {
if (!map) return;
console.log(map.getBounds());
map.on("zoomend", function () {
console.log(map.getBounds());
});
}, [map]);
Demo

How to add marker onClick and show my geolocation in google-maps-react?

I found a lot of useful information on google maps documentation but with simple use of js in html, in case of react honestly I don't understand it.
Source code:
import React, { Component } from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
export class MainMap extends Component {
render() {
return (
<div>
<h1 className="text-center">My Maps</h1>
<Map google={this.props.google}
style={{width: '80%', margin: 'auto'}}
className={'map'}
zoom={14}>
<Marker
title={'The marker`s title will appear as a tooltip.'}
name={'SOMA'}
position={{lat: 37.778519, lng: -122.405640}} />
<Marker
name={'Dolores park'}
position={{lat: 37.759703, lng: -122.428093}} />
<Marker />
<Marker
name={'Your position'}
position={{lat: 46.475640, lng: 30.759497}}/>
</Map>
</div>
);
}
}
export default GoogleApiWrapper({
apiKey: (MY-API-KEY)
})(MainMap);
i want to add marker by clicking on map and don't know how...
help please!
The map has an onClick prop which you can give a function to handle clicks on the map. The third argument to this function includes the coordinates of the click.
You could use these coordinates to add a marker to your state that you use in the render method.
Example
class MainMap extends Component {
constructor(props) {
super(props);
this.state = {
markers: [
{
title: "The marker`s title will appear as a tooltip.",
name: "SOMA",
position: { lat: 37.778519, lng: -122.40564 }
}
]
};
this.onClick = this.onClick.bind(this);
}
onClick(t, map, coord) {
const { latLng } = coord;
const lat = latLng.lat();
const lng = latLng.lng();
this.setState(previousState => {
return {
markers: [
...previousState.markers,
{
title: "",
name: "",
position: { lat, lng }
}
]
};
});
}
render() {
return (
<div>
<h1 className="text-center">My Maps</h1>
<Map
google={this.props.google}
style={{ width: "80%", margin: "auto" }}
className={"map"}
zoom={14}
onClick={this.onClick}
>
{this.state.markers.map((marker, index) => (
<Marker
key={index}
title={marker.title}
name={marker.name}
position={marker.position}
/>
))}
</Map>
</div>
);
}
}
const App = GoogleApiWrapper({
apiKey: (MY-API-KEY)
})(MainMap);

Categories