首页 > 解决方案 > 如何在我的页面上重新对齐这张传单地图?

问题描述

我使用 Leaflet 地图在地图上显示我的用户给出的位置。但是,当我加载地图并将其置于用户标记的中心时,它不在地图的中心,而是在左上角。有关更多详细信息,请参阅此视频:https ://imgur.com/a/2wTysTA

这是我的代码和地图的 css。

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/leaflet@1.6.0/dist/leaflet.css"
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
    crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.6.0/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;
}

标签: javascripthtmlcssreactjsleaflet

解决方案


推荐阅读