【发布时间】:2016-11-07 13:25:21
【问题描述】:
我正在尝试使用 react-google-maps 呈现 Google 地图。
在地图完全加载之前,我使用geolocation.navigator 函数获取用户当前位置,但我需要使用用户位置作为中心和预设缩放级别(例如 5)来计算地图的边界。
我怎样才能做到这一点?
【问题讨论】:
标签: javascript google-maps reactjs
我正在尝试使用 react-google-maps 呈现 Google 地图。
在地图完全加载之前,我使用geolocation.navigator 函数获取用户当前位置,但我需要使用用户位置作为中心和预设缩放级别(例如 5)来计算地图的边界。
我怎样才能做到这一点?
【问题讨论】:
标签: javascript google-maps reactjs
最简单的方法是在 Google 地图组件上将默认缩放设置为 5:
<GoogleMap
ref="map"
defaultZoom={5}
defaultCenter={{ lat: -25.363882, lng: 131.044922 }}
>
defaultCenter 是这种格式的用户位置。
然后得到这样的边界:
let map = this.refs.map;
let bounds = map.getBounds();
let geoBounds = {
swLat: bounds.getSouthWest().lat(),
swLng: bounds.getSouthWest().lng(),
neLat: bounds.getNorthEast().lat(),
neLng: bounds.getNorthEast().lng(),
};
【讨论】:
undefined错误。我的用例是我想在地图加载时显示集群数据,这些数据是从我在 nodejs 中的后端 api 中获取的,其中地图边界是参数。
最后,这就是我设法手动计算地图边界的方法,给定一个中心,然后由navigator.geolocation.getCurrentPosition 函数返回。
此计算基于纬度到公里的转换,其中 1 度的纬度变化约等于 111.2 公里。我正在从 10 公里宽的 latLng 计算地图的边界。
const geolocation = (
navigator.geolocation ?
navigator.geolocation :
({
getCurrentPosition(success, failure) {
failure(`Your browser doesn't support geolocation.`);
},
})
);
geolocation.getCurrentPosition(
(position) => {
if (this.isUnmounted) { return; }
this.setState({
center: {
lat: position.coords.latitude,
lng: position.coords.longitude,
}
});
// formula to find the South west and North East points from lat,lon between 10km.
let lat_change = 10/111;
let lon_change = Math.abs(Math.cos(this.state.center.lat *(Math.PI/180)));
let sw_lat = this.state.center.lat - lat_change;
let sw_lon = this.state.center.lng - lon_change;
let ne_lat = this.state.center.lat + lat_change;
let ne_lon = this.state.center.lng + lon_change;
console.log(sw_lat, sw_lon, ne_lat, ne_lon);
console.log(this.state.center);
},
(reason) => {
if (this.isUnmounted) { return; }
this.setState({
center: geoMap.INITIAL_CENTER,
zoom: 5
});
}
);
您也可以选择加载器或微调器,直到地图完全加载,然后像 cmets 中提到的 @Fabian 一样 getBounds。
【讨论】:
这就是我使用 react google map 的方式:
centralizeOnMyLocation = () => {
const { maps, map } = this.state;
const { userLocation } = this.props;
const center = {
lat: userLocation.latitude,
lng: userLocation.longitude,
};
const extendedZoomAccuracy = 0.005;
const bounds = new maps.LatLngBounds();
bounds.extend(center);
if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
const extendPoint = new google.maps.LatLng(
bounds.getNorthEast().lat() + extendedZoomAccuracy,
bounds.getNorthEast().lng() + extendedZoomAccuracy
);
bounds.extend(extendPoint);
}
map.fitBounds(bounds);
map.setCenter(center);
};
【讨论】: