簡體   English   中英

在 google-map-react 中向 Google 地圖添加標記

[英]Adding Marker to Google Maps in google-map-react

我正在使用google-map-react NPM 包來創建一個谷歌地圖和幾個標記。

問題:我們如何將默認的 Google 地圖標記添加到地圖中?

從這個 Github issue來看,我們似乎需要使用onGoogleApiLoaded函數來訪問內部的 Google Maps API。

參考Google Maps JS API docs 中的一個示例,我們可以使用以下代碼來呈現標記,但是我們如何定義對map的引用?

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
});

當前代碼:

renderMarkers() {
    ...
}

render() {
    return (
        <div style={{'width':800,'height':800}}>
            <GoogleMap
                bootstrapURLKeys={{key: settings.googleMapApiKey}}
                defaultZoom={13}
                defaultCenter={{ 
                    lat: this.props.user.profile.location.coordinates[1], 
                    lng: this.props.user.profile.location.coordinates[0]
                }}
                onGoogleApiLoaded={({map, maps}) => this.renderMarkers()}
                yesIWantToUseGoogleMapApiInternals
            >
            </GoogleMap>
        </div>
    );
}

編輯:
由於此答案已發布,因此GoogleMapReact元素的文檔(可能還有 API)已更改為支持子項。 任何具有latlng孩子都將在地圖上的相應位置呈現,正如@Jobsamuel 的回答所示。

不應將onGoogleApiLoaded回調用於此目的,因為它不如聲明式樣式,並且如果對地圖進行更改則不會重新運行。


原始答案(過時):

這從自述文件中的描述中可能並不完全清楚,但實際上, maps參數是地圖 API 對象(當然, map是當前的 Google 地圖實例)。 因此,您應該將兩者都傳遞給您的方法:

onGoogleApiLoaded={({map, maps}) => this.renderMarkers(map, maps)}

並使用它們:

renderMarkers(map, maps) {
  let marker = new maps.Marker({
    position: myLatLng,
    map,
    title: 'Hello World!'
  });
}

在地圖上添加標記並不像我們想要的那么容易,主要是因為文檔令人困惑,但這里有一個非常簡單的示例:

const Map = props => {
  return (
    <GoogleMapReact
     bootstrapURLKeys={{ props.key }}
     defaultCenter={{lat: props.lat, lng: props.lng}}
     defaultZoom={props.zoom}>

       {/* This is the missing part in docs:
         *
         * Basically, you only need to add a Child Component that
         * takes 'lat' and 'lng' Props. And that Component should
         * returns a text, image, super-awesome-pin (aka, your marker).
         *
         */}
       <Marker lat={props.lat} lng={props.lng}} />
    </GoogleMapReact>
  )
}

const Marker = props => {
  return <div className="SuperAwesomePin"></div>
}
import React from 'react';
import GoogleMapReact from 'google-map-react';

const GoogleMaps = ({ latitude, longitude }) => {
 const renderMarkers = (map, maps) => {
  let marker = new maps.Marker({
  position: { lat: latitude, lng: longitude },
  map,
  title: 'Hello World!'
  });
  return marker;
 };

 return (
   <div style={{ height: '50vh', width: '100%' }}>
    <GoogleMapReact
      bootstrapURLKeys={{ key: 'YOUR KEY' }}
      defaultCenter={{ lat: latitude, lng: longitude }}
      defaultZoom={16}
      yesIWantToUseGoogleMapApiInternals
      onGoogleApiLoaded={({ map, maps }) => renderMarkers(map, maps)}
    >
    </GoogleMapReact>
   </div>
 );
};

export default GoogleMaps;

基於MasterAM的回答。

如果您使用 react 鈎子,這個可以解決問題:

import React, { useMemo, useEffect } from 'react';

const createControlledPromise = () => {
  let resolver;
  let rejector;
  const promise = new Promise((resolve, reject) => {
    resolver = resolve;
    rejector = reject;
  });
  return { promise, resolver, rejector };
};

const useMarker = ({ lat, lng }) => {
  const { 
    promise: apiPromise, 
    resolver: handleGoogleApiLoaded 
  } = useMemo(
    createControlledPromise,
    []
  ).current;

  useEffect(
    () => {
      let marker;
      apiPromise.then(api => {
        const { map, maps } = api;
        marker = new maps.Marker({ position: { lat, lng }, map });
      });
      return () => {
        if (marker) {
          marker.setMap(null);
        }
      };
    },
    [lat, lon],
  );
  return { handleGoogleApiLoaded };
};

const Location = ({
  location: { locationName, lat, lng }
}) => {
  const { handleGoogleApiLoaded } = useMarker({ lat, lng });
  return (
    <section>
      <h1>{locationName}</h1>
      <p>
        <GoogleMapReact
          bootstrapURLKeys={{ key: __GOOGLE_MAP_API_KEY__ }}
          center={{ lat, lng }}
          defaultZoom={11}
          onGoogleApiLoaded={handleGoogleApiLoaded}
        />
      </p>
    </section>
  );
};

Gleb Lobastov在嘗試您提出的解決方案時。 我在打字稿上收到以下錯誤。 謝謝。

屬性'current'不存在於類型'{promise; Promise; 解析器:未定義; 拒絕者:未定義; }'。ts(2339)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM