[英]Using Google Map API inside a React component
我正在努力在React組件中使用Google Map API的方式。 我不想使用流行的react-google-maps
或google-map-react
包,而是創建自己的包。
我設法通過React組件使用Google Map API加載了腳本標簽。 但是,如何從此處操作Google API? 例如,使用以下基本配置初始化地圖?
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
這是我的組件。 任何建議表示贊賞! 謝謝!
import React, { Component } from 'react'; // Load Google API in script tag and append function loadScript(src) { return new Promise((resolve, reject) => { let script = document.createElement('script'); script.src = src; script.addEventListener('load', function() { resolve(); }); script.addEventListener('error', function(e) { reject(e); }); document.body.appendChild(script); }); } const script = 'https://maps.googleapis.com/maps/api/js?key=MY_API_KEY'; class MyGoogleMap extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { // first load the script into html loadScript(script).then(function() { console.log('SUCCESS'); // Where do I go from here? }); } render() { return <div />; } } export default MyGoogleMap;
使用ref創建GoogleMap組件,以在該div中顯示google map。
import React, { Component } from 'react';
class GoogleMap extends Component {
componentDidMount() {
new google.maps.Map(this.refs.map, {
zoom: 12,
center: {
lat: this.props.lat,
lng: this.props.lon
}
});
}
render() {
return <div className="google-map" ref="map" />
}
}
export default GoogleMap;
在喜歡的組件中使用它:
<GoogleMap lat={lat} lon={lon}/>
通過城市的緯度和經度。 為了能夠看到它,您需要設置CSS類google-map
寬度和高度(或任何您命名的名稱)。 例如:
div.google-map {
height: 150px;
width: 250px;
}
編輯
內部頭部加載腳本:
<script src="https://maps.googleapis.com/maps/api/js"></script>
我相信您已經做到了,因為在您的代碼中您還使用了new google.maps...
如果您不能像Google那樣調用它,請嘗試new window.google.maps...
我實際上找到了自己的解決方案,所以我將與遇到相同問題的任何人共享。
基本邏輯是使用window
對象訪問google
。 因此,按照問題的要求加載腳本后,我將地圖初始化為:
initMap = () => { // 'google' could be accessed from 'window' object const map = new window.google.maps.Map( document.getElementById('googleMap'), { zoom: 14, center: { lat: LATITUDE, lng: LONGTITUDE } } ); // putting a marker on it const marker = new window.google.maps.Marker({ position: { lat: LATITUDE, lng: LONGTITUDE }, map: map }); }; render() { return ( <div id="googleMap" style={width: WIDTH, height: HEIGHT}/> ); }
歡迎任何評論:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.