I tried to use function component to load the leafletmap but got an error saying "Map container not found". I found a solution which is to add <div id="map">
to DOM. I couldn't find a way to do this in function component. I ended up using class component to do this, and it works:
import React from "react";
import L, { LeafletMouseEvent } from "leaflet";
import "leaflet/dist/leaflet.css";
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";
let DefaultIcon = L.icon({
iconUrl: icon,
shadowUrl: iconShadow,
});
class LeafletMap extends React.Component {
componentDidMount() {
this.map();
}
map() {
L.Marker.prototype.options.icon = DefaultIcon;
var mapSW = new L.Point(0, 960),
mapNE = new L.Point(960, 0);
var map = L.map("map", { crs: L.CRS.Simple }).setView([0, 0], 4);
L.tileLayer("/assets/maps/map0/{z}/{x}/{y}.png", {
tileSize: 32,
minZoom: 4,
maxZoom: 5,
noWrap: true,
}).addTo(map);
var maxBounds = L.latLngBounds(
map.unproject(mapSW, map.getMaxZoom()),
map.unproject(mapNE, map.getMaxZoom())
);
map.setMaxBounds(maxBounds);
var marker = L.marker([0, 0], {
draggable: true,
}).addTo(map);
marker.bindPopup("<b>Our hero!</b>").openPopup();
function onMapClick(e: LeafletMouseEvent) {
let tileSize = new L.Point(32, 32);
let pixelPoint = map.project(e.latlng, map.getMaxZoom()).floor();
let coords = pixelPoint.unscaleBy(tileSize).floor()
alert("You clicked the map at " + coords);
}
map.on("click", onMapClick);
}
render() {
return <div id="map"></div>;
}
}
export default LeafletMap;
this is where the LeafletMap component gets called:
const comp: React.FC<RouteComponentProps> = () => {
return (
<div>
<Grid columns={2}>
<Grid.Column>
<LeafletMap/>
</Grid.Column>
// codes
</Grid>
</div>
Now I need to use hook features so I have to use function component. How do I solve the "Map container not found" error or add map element to DOM using function component?