Home > Software engineering >  marker not showing in React Leaflet
marker not showing in React Leaflet

Time:08-16

Added a React Leaflet map to the site. I want to put a custom marker, but now it is not shown on the page. It is always shown in the corner of the map when scrolling. How can this be fixed?

// Marker

const Marker = () => {
  return (
    <div>
      <div
        className="marker"
        style={{ height: "30px", width: "30px", backgroundColor: "red" }}
      ></div>
    </div>
  );
};

export default Marker;


// Map

const Map = () => {
  const position = [51.505, -0.09];
  return (
    <div>
      <MapContainer
        center={[51.505, -0.09]}
        zoom={13}
        scrollWheelZoom={false}
        style={{ height: "100vh", width: "100%" }}
      >
        <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={position}></Marker>
      </MapContainer>
    </div>
  );
};

export default Map;

CodePudding user response:

My snippet works perfectly, you can try this out:-

import { MapContainer, Marker, Popup, TileLayer } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import icon from "leaflet/dist/images/marker-icon.png";
import L from "leaflet";
import iconShadow from "leaflet/dist/images/marker-shadow.png";

let DefaultIcon = L.icon({
  iconUrl: icon,
  shadowUrl: iconShadow,
});

L.Marker.prototype.options.icon = DefaultIcon;

<section className="container-fluid p-0">
  <MapContainer center={[23.7934, 90.4064]} zoom={16} 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={[23.7934, 90.4064]}>
      <Popup>My Location</Popup>
    </Marker>
  </MapContainer>
</section>;
// css
.leaflet-container{
  height: 500px !important;
}
  • Related