【发布时间】:2019-11-18 22:52:38
【问题描述】:
我正在尝试在我的地图上渲染一些不同经度和纬度的标记,由于某种原因,当应用程序加载时,我在屏幕上看不到任何标记。我什至没有收到任何错误,调试时也看不到任何东西, 这是我的渲染方法的代码。
render() {
return (
<View style={styles.container}>
{/* If user location data is allowed and retrieved */}
{this.state.ready && (
<MapView
provider={PROVIDER_GOOGLE}
showsUserLocation
style={styles.map}
region={{
latitude: this.state.coords.lat,
longitude: this.state.coords.lng,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
>
{this.renderVendorMarkers()}
</MapView>
)}
</View>
);
}
}
这个.state。 ready 指的是我根据某些权限设置的布尔属性。
渲染标记的方法是“this.renderVendorMarkers()” 该方法的代码如下:
renderVendorMarkers = () => {
const { locations } = this.state;
this.getCoordinates(locations).then(coords => {
return (
<View>
{coords.map((coord, idx) => {
return (
<Marker
key={idx}
coordinate={{ latitude: coord.lat, longitude: coord.lng }}
/>
);
})}
</View>
);
});
};
此方法引用了一个位置属性,该属性链接到一个带有用户完整地址的 json 文件和另一个名为 getCoordinates 的方法,该方法返回与 google.maps api 对应的一组 promise 以获取地址。
getCoordinates = vendors => {
const APIKEY = "myApiKey"; //Put a fake value here but in code, use a real API key
const promises = vendors.map(async vendor => {
const vendorID = vendor.VendorID;
const fullAddress = `${vendor.VendorAddress},${vendor.VendorCity},${vendor.VendorState}`;
try {
const resp = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${fullAddress}&key=${APIKEY}`
);
const respJson = await resp.json();
return respJson.results[0].geometry.location;
} catch (err) {
console.log(err);
}
});
return Promise.all(promises);
};
基本上,我有一个包含用户地址列表的 json 文件。我想用用户的经度和纬度在地图上放置标记。
我的 getCoordinates 方法按我想要的方式工作。似乎问题出在 renderVendorMarkers 方法上。循环遍历坐标列表(从 getCoordinates 方法检索)时,标记不会呈现。如果您希望我进一步澄清,请告诉我。感谢您的帮助。
【问题讨论】:
-
您不能使用像
.then这样的异步代码进行渲染 - 渲染代码需要同步。您可能想在像componentDidMount这样的组件生命周期方法中调用this.getCoordinates,然后使用结果调用setState。在异步getCoordinates完成并调用setState之后,您的renderVendorMarkers应根据this.state中的更新值呈现。 -
非常感谢。这似乎奏效了。我对 react-native 还是很陌生。这让我发疯了。我确实像你建议的那样。在我将状态设置为坐标的 componentDidMount() 中添加了对 getCoordinates 的调用。然后在 render 方法中调用了 renderVendorMarker 方法,它工作得很好。
标签: javascript react-native react-native-maps