Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Añadir mapas Open Street Maps con Leaftlet en React y también compatible con Next.js

Tiempo de lectura: 2 minutos

Hoy vamos a aprender cómo podemos crear un componente de Mapas compatible con Open Street Maps usando la librería Leaftlet en React.

Lo primero que tenemos que hacer es instalar la librería necesaria:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install react react-dom leaflet
npm install react react-dom leaflet
npm install react react-dom leaflet

Y después la librería Leaflet:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install react-leaflet
npm install react-leaflet
npm install react-leaflet

Y si necesitamos TypeScript (en mi caso sí) instalamos lo siguiente:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install -D @types/leaflet
npm install -D @types/leaflet
npm install -D @types/leaflet

Instalamos los iconos:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install leaflet-defaulticon-compatibility
npm install leaflet-defaulticon-compatibility
npm install leaflet-defaulticon-compatibility

Ahora podemos crear un nuevo componente llamado Map.tsx

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet';
import "leaflet/dist/leaflet.css"
import "leaflet-defaulticon-compatibility"
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css"
//Definimos los tipos de datos que va a recibir el componente en forma de interfaz
interface Props {
latitud: number;
longitud: number;
}
function Map({ latitud, longitud }: Props) {
return (
<MapContainer center={[latitud, longitud ]} zoom={13} scrollWheelZoom={false}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[latitud, longitud ]}>
<Popup>
CSS3 popup, customizable
</Popup>
</Marker>
</MapContainer>
);
}
export default Map;
import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet'; import "leaflet/dist/leaflet.css" import "leaflet-defaulticon-compatibility" import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css" //Definimos los tipos de datos que va a recibir el componente en forma de interfaz interface Props { latitud: number; longitud: number; } function Map({ latitud, longitud }: Props) { return ( <MapContainer center={[latitud, longitud ]} zoom={13} scrollWheelZoom={false}> <TileLayer attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> <Marker position={[latitud, longitud ]}> <Popup> CSS3 popup, customizable </Popup> </Marker> </MapContainer> ); } export default Map;
import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet';
import "leaflet/dist/leaflet.css"
import "leaflet-defaulticon-compatibility"
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css"


//Definimos los tipos de datos que va a recibir el componente en forma de interfaz
interface Props {
    latitud: number;
    longitud: number;
}

function Map({ latitud, longitud }: Props) {
    return (
        <MapContainer center={[latitud, longitud ]} zoom={13} scrollWheelZoom={false}>
            <TileLayer
                attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <Marker position={[latitud, longitud ]}>
                <Popup>
                   CSS3 popup, customizable
                </Popup>
            </Marker>
        </MapContainer>
    );
}

export default Map;

Ahora hemos creado un mapa de ejemplo, para que funcione tendremos que poner:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<Map latitud={51.505} longitud={-0.09}/>
<Map latitud={51.505} longitud={-0.09}/>
<Map latitud={51.505} longitud={-0.09}/>

Si necesitamos que sea compatible con Next.js, tendremos que utilizarlo de la siguiente manera:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const MapaDinamico = useMemo(() => dynamic(
() => import('@/components/elements/Map'),
{
loading: () => <p>Cargando...</p>,
ssr: false
}
), [])
const MapaDinamico = useMemo(() => dynamic( () => import('@/components/elements/Map'), { loading: () => <p>Cargando...</p>, ssr: false } ), [])
  const MapaDinamico = useMemo(() => dynamic(
    () => import('@/components/elements/Map'),
    {
      loading: () => <p>Cargando...</p>,
      ssr: false
    }
  ), [])

Construimos dinámicamente el mapa desactivando Server Side Rendering.

E importamos el mapa de esta forma:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<Map latitud={51.505} longitud={-0.09}/>
<Map latitud={51.505} longitud={-0.09}/>
<Map latitud={51.505} longitud={-0.09}/>
0

Deja un comentario