REACT - 使用地理编码将地址转换为坐标,然后将其传递给“google-maps-react”的地图组件在地图上显示位置

发布于 2025-01-12 14:53:14 字数 3373 浏览 0 评论 0原文

我正在尝试使用“geocode”api将地址列表转换为坐标,然后使用“google-maps-react”的“Map”组件在谷歌地图上显示,我成功地转换为坐标,但是当我传递这些坐标时到“initialCenter”支撑地图返回空白...

我的父组件“ListItem”看起来像这样:-

import React, { useEffect, useState } from "react";
import STYLES from "./listItem.scss";
import { IoLocationSharp } from "react-icons/io5";
import MapItem from "../MapItem/MapItem";
import { GoogleApiWrapper } from "google-maps-react";
import Geocode from "react-geocode";
Geocode.setApiKey("MY API KEY");

const ListItem = ({ item }) => {
  const getClassName = (className) => STYLES[className] || "UNKNOWN";
  const [address, setAddress] = useState(
    `${item.street} ${item.suburb} ${item.postcode}`
  );
  const [coordinates, setCoordinates] = useState(null);
  //find coordinates from the address
  Geocode.setRegion("au");
  Geocode.setLocationType("ROOFTOP");
  const findLatAndLng = () => {
    Geocode.fromAddress(address).then(
      (response) => {
        setCoordinates(response.results[0].geometry.location);
      },
      (error) => {
        console.error(error);
      }
    );
  };

  useEffect(() => {
    findLatAndLng();
  }, [address]);

  return (
    <div className={getClassName("listContainer")}>
      <div className={getClassName("listItemIcon")}>
        <IoLocationSharp />
      </div>
      <div className={getClassName("listItemDetails")}>
        <h3 className="name">{item.name} </h3>
        <span className={getClassName("street")}>{item.street},&nbsp;</span>
        <span className={getClassName("suburb")}>{item.suburb},&nbsp;</span>
        <span className={getClassName("postcode")}>{item.postcode}</span>
        {item.phoneNumber && (
          <p className={getClassName("phone")}>
            {`Ph: ${item.phoneNumber.slice(0, 4)} ${item.phoneNumber.slice(
              4,
              7
            )} ${item.phoneNumber.slice(7)}`}
          </p>
        )}
        {item.faxNumber && (
          <p className={getClassName("fax")}>
            {`Fax: (${item.faxNumber.slice(0, 2)}) ${item.faxNumber.slice(
              2,
              6
            )} ${item.faxNumber.slice(6)}`}
          </p>
        )}
      </div>
      <div className={getClassName("listMap")}>
        <MapItem coordinates={coordinates} />
      </div>
    </div>
  );
};

export default GoogleApiWrapper({
  apiKey: "MY API KEY",
})(ListItem);

我的“MapItem”组件看起来像这样:

import React, { Component, useEffect, useState } from "react";
import { Map, Marker } from "google-maps-react";

const MapItem = ({ coordinates }) => {
  const mapStyles = {
    width: "130px",
    height: "130px",
  };
  const renderMap = (coordinates) => {
    return (
      <Map
        google={google}
        style={mapStyles}
        zoom={12}
        initialCenter={{ lat: coordinates?.lat, lng: coordinates?.lng }}
      >
        <Marker position={{ lat: coordinates?.lat, lng: coordinates?.lng }} />
      </Map>
    );
  };

  console.log(coordinates);
  return renderMap(coordinates);
};

export default MapItem;

-console.log(坐标)正在显示值,但我收到以下错误并且空白地图:- “setCenter:不是具有有限坐标的 LatLng 或 LatLngLiteral:在属性 lat 中:NaN 不是可接受的值”

有人可以建议这里出了什么问题吗?

I am trying to convert a list of addresses to coordinates using "geocode" api and then showing on google maps using "Map" component of "google-maps-react", I was successful in converting to the coordinates but when I pass these coordinates to "initialCenter" prop the Map return blank...

my parent component "ListItem" looks like this:-

import React, { useEffect, useState } from "react";
import STYLES from "./listItem.scss";
import { IoLocationSharp } from "react-icons/io5";
import MapItem from "../MapItem/MapItem";
import { GoogleApiWrapper } from "google-maps-react";
import Geocode from "react-geocode";
Geocode.setApiKey("MY API KEY");

const ListItem = ({ item }) => {
  const getClassName = (className) => STYLES[className] || "UNKNOWN";
  const [address, setAddress] = useState(
    `${item.street} ${item.suburb} ${item.postcode}`
  );
  const [coordinates, setCoordinates] = useState(null);
  //find coordinates from the address
  Geocode.setRegion("au");
  Geocode.setLocationType("ROOFTOP");
  const findLatAndLng = () => {
    Geocode.fromAddress(address).then(
      (response) => {
        setCoordinates(response.results[0].geometry.location);
      },
      (error) => {
        console.error(error);
      }
    );
  };

  useEffect(() => {
    findLatAndLng();
  }, [address]);

  return (
    <div className={getClassName("listContainer")}>
      <div className={getClassName("listItemIcon")}>
        <IoLocationSharp />
      </div>
      <div className={getClassName("listItemDetails")}>
        <h3 className="name">{item.name} </h3>
        <span className={getClassName("street")}>{item.street}, </span>
        <span className={getClassName("suburb")}>{item.suburb}, </span>
        <span className={getClassName("postcode")}>{item.postcode}</span>
        {item.phoneNumber && (
          <p className={getClassName("phone")}>
            {`Ph: ${item.phoneNumber.slice(0, 4)} ${item.phoneNumber.slice(
              4,
              7
            )} ${item.phoneNumber.slice(7)}`}
          </p>
        )}
        {item.faxNumber && (
          <p className={getClassName("fax")}>
            {`Fax: (${item.faxNumber.slice(0, 2)}) ${item.faxNumber.slice(
              2,
              6
            )} ${item.faxNumber.slice(6)}`}
          </p>
        )}
      </div>
      <div className={getClassName("listMap")}>
        <MapItem coordinates={coordinates} />
      </div>
    </div>
  );
};

export default GoogleApiWrapper({
  apiKey: "MY API KEY",
})(ListItem);

and my "MapItem"component looks like this:-

import React, { Component, useEffect, useState } from "react";
import { Map, Marker } from "google-maps-react";

const MapItem = ({ coordinates }) => {
  const mapStyles = {
    width: "130px",
    height: "130px",
  };
  const renderMap = (coordinates) => {
    return (
      <Map
        google={google}
        style={mapStyles}
        zoom={12}
        initialCenter={{ lat: coordinates?.lat, lng: coordinates?.lng }}
      >
        <Marker position={{ lat: coordinates?.lat, lng: coordinates?.lng }} />
      </Map>
    );
  };

  console.log(coordinates);
  return renderMap(coordinates);
};

export default MapItem;

console.log(coordinates) is showing values but i am getting following error and a blank map:-
"setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: NaN is not an accepted value"

Can anybody suggest what is wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苯莒 2025-01-19 14:53:14

好吧,解决方案有点简单,我必须首先检查坐标是否为空......

coordinates && (
        <Map
          google={google}
          style={mapStyles}
          zoom={12}
          initialCenter={{
            lat: coordinates?.lat,
            lng: coordinates?.lng,
          }}
        >
          <Marker
            position={{
              lat: coordinates?.lat,
              lng: coordinates?.lng,
            }}
          />
        </Map>
      )

Well the solution was kind of simple i had to intially check the coordinates if its empty or not...

coordinates && (
        <Map
          google={google}
          style={mapStyles}
          zoom={12}
          initialCenter={{
            lat: coordinates?.lat,
            lng: coordinates?.lng,
          }}
        >
          <Marker
            position={{
              lat: coordinates?.lat,
              lng: coordinates?.lng,
            }}
          />
        </Map>
      )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文