mihuj
mihuj

Reputation: 33

GeoJSON marker is not showing on my leafletjs map

I'm writing my first larger project in react and I need to set up markers in my map component. I've set everythin up as it is shown in the tutorial however it is not working correctly with my code and the markers are not shown on map.

const dummyGeoJson = {
  type: "FeatureCollection",
  features: [
    {
      type: "Feature",
      properties: {},
      geometry: {
        type: "Point",
        coordinates: [16.959285736083984, 52.40472293138462]
      }
    }
  ]
};

class EventMap extends React.Component {
  componentDidMount() {
    this.map = L.map("map", {
      center: [51.9194, 19.1451],
      zoom: 6
    });

    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      maxZoom: 20
    }).addTo(this.map);
    var geoJsonLayer = L.geoJSON().addTo(this.map);
    geoJsonLayer.addData(dummyGeoJson);
  }

  render() {
    return <Wrapper width="100%" height="800px" id="map" />;
  }
}

From what i've read in official leaflet tutorial this code should create a new geojson layer and create a marker in a position referenced in geojson but actually the only thing that is shown is my tile layer.

Upvotes: 1

Views: 1916

Answers (2)

ghybs
ghybs

Reputation: 53290

Welcome to SO!

The most probable reason is that you bundle your app (typically with webpack), but the build misses Leaflet default icon images.

So your Marker is there, but you cannot see it because its icon image is missing.

An easy way to debug it is to use another icon instead, as suggested in kboul's answer, or even more simply by using a CircleMarker.

Then to solve the issue of the build engine missing to process the default icon images, see Leaflet #4968:

  • explicitly import / require the Leaflet default icon images and modify the L.Icon.Default options to use the new imported paths
  • or use the leaflet-defaulticon-compatibility plugin (I am the author).

Upvotes: 0

kboul
kboul

Reputation: 14600

You need to use a pointToLayer function in a GeoJSON options object when creating the GeoJSON layer like this:

componentDidMount() {
    const map = L.map("map", {
      center: [51.9194, 19.1451],
      zoom: 6
    });

    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      maxZoom: 20
    }).addTo(map);

    L.geoJSON(dummyGeoJson, {
      pointToLayer: (feature, latlng) => {
        return L.marker(latlng, { icon: customMarker });
      }
    }).addTo(map);
}

You can then pass a customMarker variable to define some options in order to make your marker be displayed on the UI

Demo

Upvotes: 0

Related Questions