You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Next.js动态页面中将经纬度传递给Leaflet地图组件

解决步骤

核心是通过React组件props传递经纬度参数,总共需要修改两个文件:

1. 修改 /pages/map/[id].jsx

改动点:

  • 将dynamic导入逻辑移到组件外部,避免重复渲染时重复导入
  • 把接口拿到的经纬度参数传递给Map组件
  • 以下代码默认你接口返回的经纬度字段为lat(纬度)、lng(经度),如果实际字段名不同替换为你自己的字段即可

修改后完整代码:

import Image from "next/image";
import dynamic from "next/dynamic";
// 把dynamic导入移到组件外部
const Map = dynamic(
  () => import('../../components/Map'),
  { ssr: false }
)

export default function soloRefugio({ data }) {
  const currentData = data[0]
  return (
    <Layout>
      <article>
        <Image
          priority
          src={currentData.Imagen.name}
          height={400}
          width={400}
          alt="imagen"
        />
        <h1>{currentData.Nombre}</h1>
        <p>P: {currentData.Pro}</p>
        <p>A: {currentData.Alt}</p>
        {/* 传递经纬度给Map组件 */}
        <Map lat={currentData.lat} lng={currentData.lng} />
      </article>
    </Layout>
  );
}

// 原有getStaticPaths、getStaticProps逻辑无需修改
export async function getStaticPaths() {
  try {
    const res = await fetch("http://localhost:1337/ref");
    const data = await res.json();
    const paths = data.map(({ slug }) => ({ params: { id: slug } }));

    return {
      paths,
      fallback: false,
    };
  } catch (error) {
    console.log(error);
  }
}

export async function getStaticProps({ params }) {
  try {
    const res = await fetch("http://localhost:1337/ref?slug=" + params.id);
    const data = await res.json();
    return {
      props: {
        data: data,
      },
    };
  } catch (error) {
    console.log(error);
  }
}

2. 修改 /components/Map.jsx

改动点:

  • 组件接收lat、lng参数
  • 把原来写死的地图中心点、标记点坐标替换为传入的动态参数
  • 新增了通用问题修复:解决Leaflet默认标记图标不显示的问题
  • 新增了坐标更新逻辑:如果后续经纬度参数变化,地图会自动切换中心点

修改后完整代码:

import { MapContainer, Marker, Popup, TileLayer, useMap } from 'react-leaflet'
import 'leaflet/dist/leaflet.css'
import L from 'leaflet'

// 修复Leaflet默认标记图标缺失问题
delete L.Icon.Default.prototype._getIconUrl
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
  iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
  shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
})

// 坐标变化时自动更新地图中心点
function UpdateMapCenter({ lat, lng }) {
  const map = useMap()
  map.setView([lat, lng], 13)
  return null
}

const Map = ({ lat, lng }) => {
  return (
    <MapContainer center={[lat, lng]} zoom={13} scrollWheelZoom={false} style={{height: 400, width: "100%"}}>
      <UpdateMapCenter lat={lat} lng={lng} />
      <TileLayer
        attribution='&copy; OpenStreetMap contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Marker position={[lat, lng]}>
        <Popup>
          当前坐标:{lat}, {lng}
        </Popup>
      </Marker>
    </MapContainer>
  )
}

export default Map

注意事项

所有修改保存后重启开发服务即可生效,如果页面加载异常请先检查接口返回的经纬度字段名是否和代码中使用的一致。

内容的提问来源于stack exchange,提问作者El Pelusa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:54:05