我在我的应用中使用react-google-maps
软件包。我想访问Map.setZoom()方法,但得到
TypeError:对象不支持属性或方法“ setZoom”
有趣的是,Map.panTo()
方法很好用。它们都应该是Map对象的成员。
https://developers.google.com/maps/documentation/javascript/reference/3.exp/map#Map.panTo https://developers.google.com/maps/documentation/javascript/reference/3.exp/map#Map.setZoom
withHandlers(() => {
const refs = {
map: undefined
}
return {
onMapMounted: () => ref => {
refs.map = ref
},
onClick: () => () => {
console.log("Getting location...");
navigator.geolocation.getCurrentPosition(
position => {
const coords = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log(coords);
refs.map.panTo(coords); // This line works
refs.map.setZoom(8); // This line throws a Type Error
},
error => {
console.log("Error" + error.code);
}
);
}
}
}),
...
这是我整个组件的定义,大致基于react-google-maps
文档https://tomchentw.github.io/react-google-maps/#googlemap
const Map = compose(
withProps({
googleMapURL: `${url}`,
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withHandlers(() => {
const refs = {
map: undefined
}
return {
onMapMounted: () => ref => {
refs.map = ref
},
onClick: () => () => {
console.log("Getting location...");
navigator.geolocation.getCurrentPosition(
position => {
const coords = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log(coords);
refs.map.panTo(coords);
refs.map.setZoom(8);
},
error => {
console.log("Error" + error.code);
}
);
}
}
}),
withScriptjs,
withGoogleMap
)((props) =>
<GoogleMap
defaultZoom={4}
defaultCenter={DefaultCoords}
ref={props.onMapMounted}
>
<OverlayView
position={DefaultCoords}
mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
getPixelPositionOffset={getPixelPositionOffset}
>
<div style={{ background: `white`, border: `1px solid #ccc`, padding: 15 }}>
<button onClick={props.onClick}>Use GPS</button>
</div>
</OverlayView>
{props.isMarkerShown && <Marker position={DefaultCoords} />}
</GoogleMap>
);
答案 0 :(得分:0)
react-google-maps
库的独立GoogleMap
class尚未公开setZoom
方法。
一种解决方案是直接访问google.maps.Map
类,并设置缩放,如下所示:
1)可以访问google.maps.Map
实例:
onMapMounted: () => ref => {
refs.map = ref
refs.mapObject = ref.context[MAP]; //<-access google.maps.Map instance
}
2),其中MAP
是来自以下内容的常量:
import {MAP} from 'react-google-maps/lib/constants'
3)设置缩放比例:
refs.mapObject.setZoom(8);