0

I use the Leaflet map to display, on a map, a position given by my user. However, when I load the map and center it on the marker of the user, it is not in the center of my map, but in the top-left corner. See this video for more details : https://i.sstatic.net/jAtRT.jpg

Here is my code and the css for the map.

import React, { Component } from 'react'
import L from 'leaflet'

export class VolontariusMap extends Component {
  componentDidMount() {
    this.map = L.map('mapid', {
      center: [49.8419, 24.0315],
      zoom: 16,
      layers: [
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
          attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        }),
      ]
    })
  }

  componentWillReceiveProps(nextProps) {
    var lon = nextProps.lon;
    var lat = nextProps.lat;
    if(lon != this.props.lon && lat != this.props.lat) {
      this.map.panTo(new L.LatLng(lat, lon));
      L.marker([lat, lon]).addTo(this.map);     
      this.map.invalidateSize(); 
    }
  }
    render() {      
        return (
          ""
        )
    }
}

export default VolontariusMap

<div id="mapid"></div>
<VolontariusMap lon={this.state.offer.lon} lat={this.state.offer.lat} />
<!DOCTYPE html>
<html>
  <head>
    <title>Volontarius</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
    crossorigin=""/>
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
   integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
   crossorigin=""></script>
    <script src="https://kit.fontawesome.com/ba635d3828.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div id="root"></div>
    <script src="./src/index.js"></script>
  </body>
</html>

#mapid {
    height: 400px;
}
5
  • Its L.latLng(lat, lon), not new L.LatLng(lat, lon).
    – StackSlave
    Commented Jan 6, 2020 at 21:36
  • @StackSlave the same thing is still happening...
    – user11936976
    Commented Jan 6, 2020 at 21:39
  • @StackSlave The two constructs are functionally identical.
    – peeebeee
    Commented Jan 6, 2020 at 22:32
  • You can try to replace this.map.panTo(new L.LatLng(lat, lon)); with this.map.setView([lat, lon]); Commented Jan 7, 2020 at 7:56
  • 1
    Looks like a missing invalidateSize. See stackoverflow.com/questions/36246815/… and stackoverflow.com/questions/56176938/… Commented Jan 7, 2020 at 9:31

0