Simple React-Leaflet Location Picker Setup

Hi everyone,

Just thought I’d share a very simple react-leaflet setup in case it’s able to help anyone.

screencast-localhost_3889-2019.08.24-14_01_41.gif

Add the css and javascript for leaflet to public > index.html:

  
https://unpkg.com/leaflet@1.5.1/dist/leaflet.js">https://unpkg.com/leaflet@1.5.1/dist/leaflet.js

Install react-leaflet via npm or yarn, also add the dependencies:

npm install react-leaflet # npm
npm install leaflet react react-dom # npm

yarn add react-leaflet # Yarn
yarn add leaflet react react-dom # Yarn

Create the map component:

import React, { useState } from 'react'
import { Map, TileLayer, Marker, Popup } from 'react-leaflet'


const MapSimple = () => {

    const [location, setLocation] = useState({
        lat: 51.505,
        lng: -0.09,
        zoom: 13,
    });
    const position = [location.lat, location.lng];
    
    const setMarkerPosition = e => {
        setLocation({ ...e.latlng, zoom: 19 });
        console.log(`My location is: ${JSON.stringify(e.latlng, null, 3)}`)
    };

    return (
        
            <TileLayer
                attribution='© OpenStreetMap contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            
                
                   A sample popup.
                
            
        
    )
}

export default MapSimple;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s