React.js有一套自己調用Google Map的機制。
附鏈接:https://www.npmjs.com/package/google-maps-react
首先,你需要去申請一個API key。
具體的安裝和使用方法在以上鍊接中都有,這裏主要想記錄一下標記地點的寫法。
Google Map自帶的marker可以實現標記地點的功能。
代碼如下:
import React from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
export class GMap extends React.Component {
state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {},
};
onMarkerClick = (props, marker, e) =>
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
onMapClicked = (props) => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
})
}
};
render() {
return (
<Map google={this.props.google}
initialCenter={{
lat: 39.9060115,
lng: 116.3956187
}}
zoom={16.75}
onClick={this.onMapClicked}>
<Marker onClick={this.onMarkerClick}
name={'descripton'}
position={{lat: 39.9055688, lng: 116.39749}}/>
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}>
<div>
<h3>{this.state.selectedPlace.name}</h3>
</div>
</InfoWindow>
</Map>
)
}
}
export default GoogleApiWrapper({
apiKey: (YOUR_GOOGLE_API_KEY_GOES_HERE)
})(GMap)
展示效果:
這是一個對天安門廣場進行標記的地圖。
<Map google={this.props.google}
initialCenter={{
lat: 39.9060115,
lng: 116.3956187
}}
zoom={16.75}
onClick={this.onMapClicked}>
initialCenter可以確定初始位置。
<Marker onClick={this.onMarkerClick}
name={'descripton'}
position={{lat: 39.9055688, lng: 116.39749}}/>
position確定的是標記位置。
其中lat和lng代表的是一個地點的經緯度。
那麼怎麼獲取一個地點的經緯度呢?
可以通過Google在線地圖獲取。
在搜索框中輸入想要找到的標記的名字的名字,鼠標收縮找到想要展示的頁面的收縮比例。記錄下經緯度和zoom值。
如圖所示,我希望最終展示的地圖的比例如圖所示,只需在initialCenter中記錄該地址的經緯度,以及zoom值即可。
圖中地址中包含其經緯度及z值。
然後是標記的經緯度。若想使位置更爲準確,建議將地圖放大至最大,記錄下經緯度,將其寫在marker的position中即可。
marker的形狀是可以更改的。
附鏈接:https://www.cnblogs.com/Leo_wl/p/5797870.html
查了好幾天怎麼調用地圖,怎麼標記地點,終於塵埃落定。
雖然其中原理並未完全搞懂,不過想要的效果已經出來了,算是近了一大步。