使用Marker OnPress发送标题和描述

问题描述 投票:0回答:1

我已经创建了带有react-native-maps和几个标记的应用程序。我希望能够单击标记,并弹出标记的标题和说明。从长远来看,我将从数据库中获取购物清单,并将其加载为带有地址的标记。

我尝试在标记上设置ID以进行提取,但是输出将ID显示为null。如何在弹出窗口中获取标记的详细信息?

import MapView, { AnimatedRegion } from "react-native-maps";
import { StyleSheet, Text, View, Dimensions } from "react-native";
import Geocoder from "react-native-geocoding";
import redMarker from '../assets/images/dot.png'

Geocoder.init("AIzaSyBh4LzOmbFVqu5wc_u_9S4yKT1rhbgHBuw");

class GroceryList{
  constructor(address, groceries, title, key){
    this.address = address;
    this.title = title;
    this.groceries = groceries;
    this.key = key;
  }
}

export default class MapScreen extends Component {
  constructor() {
    super();
    this.state = {
      longitude: 60.256771,
      latitude: 7.909972,
      latitudeDelta: 0.0001,
      longitudeDelta: 0.0001,
      location: null,
      locations: [],
      AllLists: [],
      title: null,
      description: null,
      key: null,
      selectedMarker: null,
    };
      this._onMarkerPress = this._onMarkerPress.bind(this);
  }

  markerClick(e) {
    console.log(e);
}

  renderMarkers(){
    return this.state.locations.map(location => {
      return <MapView.Marker 
      coordinate={{ latitude: location.lat, longitude: location.lng }}
      title={this.state.title}
      description={this.state.description}
      key={location.lat}
      image={redMarker}
      id={this.state.key}
      onPress={this._onMarkerPress}
      />
    })
}

componentDidMount = async () => {
  navigator.geolocation.getCurrentPosition(
    ({ coords }) => {
      this.setState({
        longitude: coords.longitude,
        latitude: coords.latitude,
        latitudeDelta: 0.005,
        longitudeDelta: 0.005,
      })
    },
    (error) => alert('Error: Are location services on?'),
    { enableHighAccuracy: true }
  )

  liste = []

  en = new GroceryList("Eiffel Twer", "Melk", "Min første handleliste", "1"),
  liste.push(en)

  for(const list of liste){
    this.setState(prevState => ({
      AllLists: [...prevState.AllLists, list],
    }))
  }
}

getGeoData() {
  for (const list of this.state.AllLists) {
    Geocoder.from(list.address)
      .then((response) => {
        this.setState(prevState => ({
          locations: [...prevState.locations, response.results[0].geometry.location]
        }))
        this.setState({
          title: list.title,
          description: list.groceries,
          key: list.key,
        })
      })
      .catch((error) => console.warn(error));
  }
}

componentDidUpdate(prevProps, prevState) {
  if (this.state.AllLists !== prevState.AllLists) {
    this.getGeoData();
  }
}

  render() {
      return (
        <View style={styles.container}>
          <MapView
            style={styles.mapStyle}
            region={{
              latitude: this.state.latitude, 
              longitude: this.state.longitude, 
              latitudeDelta: this.state.latitudeDelta,
              longitudeDelta: this.state.longitudeDelta}}
            showsUserLocation={true}
            showsMyLocationButton={true}
            onMarkerPress={this.markerClick}
          >
            {this.renderMarkers()}
          </MapView>
        </View>
      );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  mapStyle: {
    width: Dimensions.get("window").width,
    height: Dimensions.get("window").height,
  },
});

markerClick中console.log的输出:

  "_dispatchInstances": FiberNode {
    "tag": 5,
    "key": null,
    "type": "AIRMapMarker",
  },
  "_dispatchListeners": [Function onPress],
  "_targetInst": FiberNode {
    "tag": 5,
    "key": null,
    "type": "AIRMapMarker",
  },
  "bubbles": undefined,
  "cancelable": undefined,
  "currentTarget": 225,
  "defaultPrevented": undefined,
  "dispatchConfig": Object {
    "registrationName": "onPress",
  },
  "eventPhase": undefined,
  "isDefaultPrevented": [Function functionThatReturnsFalse],
  "isPropagationStopped": [Function functionThatReturnsFalse],
  "isTrusted": undefined,
  "nativeEvent": Object {
    "action": "marker-press",
    "coordinate": Object {
      "latitude": 58.8289179,
      "longitude": 5.7244708,
    },
    "id": null,
    "position": Object {
      "x": 567,
      "y": 1049,
    },
  },
  "target": undefined,
  "timeStamp": 1588789970785,
  "type": undefined,
}
javascript reactjs react-native dictionary markers
1个回答
0
投票
{id,title,description,lat,lng,...} these should be present on your locations array representing each marker on map and then on your renderMarkers function 

renderMarkers(){
    return this.state.locations.map(location => {
      return <MapView.Marker 
      coordinate={{ latitude: location.lat, longitude: location.lng }}
      title={this.state.title}
      description={this.state.description}
      key={location.lat}
      image={redMarker}
      id={this.state.key}
      onPress={() => this._onMarkerPress(location)} // check this
      />
    })

    _onMarkerPress = (location) => console.log("pressed 
    marker details : ",location); 
© www.soinside.com 2019 - 2024. All rights reserved.