Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

277
Visualizações
Location me in map from React Leaflet

I want to ask if I use a map from React Leaflet (https://react-leaflet.js.org/) but how do I add a location button to the map? like this an example of the location me button in the image that I gave the red arrow

And pictures in the link:
Example of an arrow Location Me

An example on my map where I want to add location Me

And how to show the location button, where do you save it from my coding?

import { React, useState } from 'react'
import {
  LayersControl,
  MapContainer,
  Marker,
  Popup,
  TileLayer,
  useMapEvents,
} from 'react-leaflet'

const { BaseLayer } = LayersControl

function LocationMarker() {
  const [position, setPosition] = useState(null)
  const map = useMapEvents({
    click() {
      map.locate()
    },
    locationfound(e) {
      setPosition(e.latlng)
      map.flyTo(e.latlng, map.getZoom())
    },
  })

  return position === null ? null : (
    <Marker position={position}>
      <Popup>You are here</Popup>
    </Marker>
  )
}


function MapsMe() {
  return (
    <div className="flex ml-auto">
      <div className="w-4/5">
        <MapContainer center={51.505, -0.09} zoom=20>
          <LayersControl>
            <BaseLayer checked name="OpenStreetMap">
              <TileLayer
                attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png "
              />
            </BaseLayer>
            <LocationMarker />
          </LayersControl>
        </MapContainer>
      </div>
    </div>
  )
}

export default MapsMe

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you need to get the exact same result as in your picture you need to use leaflet-easybutton library with font-awesome. Otherwise you can easily build your own icon by extending leaflet control.

Install them:

npm i leaflet-easybutton

npm i font-awesome

Import them:

import "leaflet-easybutton/src/easy-button.js";
import "leaflet-easybutton/src/easy-button.css";
import "font-awesome/css/font-awesome.min.css";

Instantiate L.easy-button using fa-map-marker icon and inside the callback save the position and move the map to the user location.

export default function Map() {
  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 (
    <MapContainer
      center={[51.505, -0.09]}
      zoom={20}
      style={{ height: "100vh" }}
      whenCreated={setMap}
    >
    ...
}

Here is a demo. When you open it the icon won't show up cause there is a known issue with svg icons and codesandbox but locally you should not have any issue.

about 4 years ago · Juan Pablo Isaza Relatório

0

This is how I solve the same issue. Created a resusable component for leaflet controls. Just a fancy way to easily handle leaflets classes.

import L from "leaflet";
import React, { useEffect, useRef } from "react";

const ControlClasses = {
  bottomleft: "leaflet-bottom leaflet-left",
  bottomright: "leaflet-bottom leaflet-right",
  topleft: "leaflet-top leaflet-left",
  topright: "leaflet-top leaflet-right",
};

type ControlPosition = keyof typeof ControlClasses;
interface LeafLetControlProps {
  position?: ControlPosition;
}

const LeafletControl: React.FC<LeafLetControlProps> = ({
  position,
  children,
}) => {
  const divRef = useRef(null);

  useEffect(() => {
    if (divRef.current) {
      L.DomEvent.disableClickPropagation(divRef.current);
      L.DomEvent.disableScrollPropagation(divRef.current);
    }
  });

  return (
    <div ref={divRef} className={position && ControlClasses[position]}>
      <div className={"leaflet-control"}>{children}</div>
    </div>
  );
};

export default LeafletControl;

Use the leaflet control component in with the functionality you want.

import { ActionIcon } from "@mantine/core";
import React, { useState } from "react";
import { useMapEvents } from "react-leaflet";
import { CurrentLocation } from "tabler-icons-react";
import LeafletControl from "./LeafletControl";

interface LeadletMyPositionProps {}

const LeadletMyPosition: React.FC<LeadletMyPositionProps> = ({}) => {
  const [loading, setLoading] = useState<boolean>(false);
  const map = useMapEvents({
    locationfound(e) {
      map.flyTo(e.latlng);
      setLoading(false);
    },
  });

  return (
    <LeafletControl position={"topright"}>
      <ActionIcon
        onClick={() => {
          setLoading(true);
          map.locate();
        }}
        loading={loading}
        variant={"transparent"}
      >
        <CurrentLocation />
      </ActionIcon>
    </LeafletControl>
  );
};

export default LeadletMyPosition;

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda