簡體   English   中英

如何顯示來自json文件的標記列表?

[英]How to show a list of markers which comes from a json file?

我正在使用airbnb制作的包react-native-maps。 鏈接在這里 :

https://github.com/airbnb/react-native-maps

當我想在地圖上顯示標記列表時遇到問題。 我做了一個像這樣的json文件進行測試:

{
    "shop_1": {
        "id": "1",
        "name": "Shop 1",
        "latitude": "48.886674",
        "longitude": "2.210269"
    },
    "shop_2": {
    ...
}

我一直在尋找一種解釋,但我不知道如何通過我的結構來實現。

MapView.Markers的API: https : //github.com/airbnb/react-native-maps/blob/master/docs/marker.md

Map.js

import React, { Component } from 'react';
import Geolocation from '../geolocation/Geolocation';
import Shops from '../shops/Shop';
import {
  Text,
  View
} from 'react-native';
import MapView from 'react-native-maps';
import styles from './Style';

class Map extends Geolocation {

  constructor(props) {
    super(props);
    this.shops = require('./data/shops.json');
  }

  render() {
    return (
      <View>
        <MapView style={styles.map}
        region={{
          latitude: this.state.position.coords.latitude,
          latitudeDelta: 0.001,
          longitude: this.state.position.coords.longitude,
          longitudeDelta: 0.001
        }}>
          <MapView.Marker coordinate={this.state.position.coords} title="Vous êtes ici !" image={require('./img/initialMarker.png')} />

        </MapView>
        <Shops />
      </View>
    );
  }

}

export default Map;

感謝您的回答。

編輯:Geolocation.js

import React, { Component } from 'react';
import styles from './Style';

class Geolocation extends Component {

    constructor(props) {
        super(props);
        this.state = {
            position : {
                coords: {
                    latitude: 0,
                    longitude: 0
                }
            }
        }
    }

    componentDidMount() {
        navigator.geolocation.getCurrentPosition(
            (position) => {
                this.setState({position});
            },
            (error) => alert(error.message),
            {enableHighAccuracy: true, timeout: 20000}
        );
        navigator.geolocation.watchPosition((position) => {
            this.setState({position});
        });
    }
}

export default Geolocation;

首先,將您的商店以如下方式在構造函數中聲明:

this.state = {
  shops: require('./data/shops.json')
};

然后像這樣在MapView中循環標記:

{this.state.shops.map(shop => {
  <MapView.Marker coordinate={{latitude: shop.latitude, longitude: shop.longitude}} image={require('./img/initialMarker.png')} />
})}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM