Моя карта не работает, когда остановить прокрутку, коды borkes - PullRequest
0 голосов
/ 10 февраля 2020

Мой код нарушается, когда onMomentumScrollEnd останавливается, и я понятия не имею, как заставить его работать.

Вот код:

import React, { Component } from 'react';
import {
  ScrollView,
  View,
  Text,
  StyleSheet,
  Dimensions,
  TouchableOpacity,
  Alert,
} from 'react-native';
import MapView from 'react-native-maps';
const locations = require('./3ªLégua-Oriental-NossaSenhoradasGraças.json');
export default class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
      locations: locations,
    };
  }
  _toastWithDurationGravityOffsetHandler = () => {

    Alert.alert('INFORMAÇÃO','Arraste para o lado para visualizar o próximo ponto no mapa.');
  };

  _mapReady = () => {
    this.state.locations[0].mark.showCallout();
  };

  render() {

    const {  latitude, longitude } = this.state.locations[0];

    return (
      <View style={styles.container}>
        <MapView
          ref={map => (this.mapView = map)}
          initialRegion={{
            latitude,
            longitude,
            latitudeDelta: 0.0142,
            longitudeDelta: 0.0231,
          }}
          style={styles.mapView}
          rotateEnabled={true}
          scrollEnabled={true}
          showsMyLocationButton={true}
          showsUserLocation={true}
          zoomEnabled={true}
          showsPointsOfInterest={false}
          showBuildings={false}
          onMapReady={this._mapReady}>
          {locations.map(
            (locations, id, latitude, longitude, hora) => (
              console.log(locations.latitude, locations.latitude),
                <MapView.Marker
                  onPress={this.handleMapPress}
                  ref={mark => (locations.mark = mark)}
                  key={id}
                  title={'Parada'}
                  description={locations.hora}
                  coordinate={{
                    latitude: JSON.parse(locations.latitude),
                    longitude: JSON.parse(locations.longitude),
                 }}>
              </MapView.Marker>
            ))}
        </MapView>

        <ScrollView
          style={styles.placesContainer}
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onMomentumScrollEnd={e => {
            const locations =
              e.nativeEvent.contentOffset.x > 0
                ? e.nativeEvent.contentOffset.x / Dimensions.get('window').width
                : 0;

            const { latitude, longitude, mark } = this.state.locations[locations];

            this.mapView.animateToCoordinate( 
              {
                latitude,
                longitude,
              },
              500
            );

            setTimeout(() => {
              mark.showCallout();
            }, 500);
          }}>
          {this.state.locations.map(locations => (
            <View key={locations.id} style={styles.place}>
              <Text style={styles.title}>Ponto {locations.id} </Text> 

              <Text style={styles.description}>{locations.hora}</Text>
              <TouchableOpacity
                style={styles.buttonStyle}
                onPress={this._toastWithDurationGravityOffsetHandler}>
                <Text> Próximo Ponto</Text>
              </TouchableOpacity>
            </View>
          ))}
        </ScrollView>
      </View>
    );
  }
}

const { height, width } = Dimensions.get('window'); 

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'flex-end',
  },
  mapView: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
  },
  placesContainer: {
    width: '100%',
    maxHeight: 120,
  },
  place: {
    width: width - 40,
    maxHeight: 150,
    backgroundColor: '#FFF',
    marginHorizontal: 20,
    borderTopLeftRadius: 5,
    borderDownLeftRadius: 5,
    borderTopRightRadius: 5,
    borderDownRightRadius: 10,

    padding: 20,
  },
  buttonStyle: {
    padding: 10,
    margin: 5,
    fontWeight: 'bold',
    borderRadius: 15,
    backgroundColor: '#FF6600',
    textAlign: 'center',
    color: 'white',
    fontSize: 20,
    alignItems: 'center',
  },
  title: {
    fontWeight: 'bold',
    fontSize: 15,
    backgroundColor: 'transparent',
  },
  description: {
    color: '#999',
    fontSize: 12,
    marginTop: 5,
  },
});

А вот мой JSON файл:

[
    {
        "id": "1",
        "latitude": "-29.271225",
        "longitude": "-51.1895903",
        "hora": "05:55:00"
    },
    {
        "id": "2",
        "latitude": "-29.2511256",
        "longitude": "-51.1932803",
        "hora": ""
    },
    {
        "id": "3",
        "latitude": "-29.2434067",
        "longitude": "-51.1985995",
        "hora": ""
    },
  ...
]

Вот ссылка на код: https://snack.expo.io/@matheus_cbrl / scroll-map

1 Ответ

0 голосов
/ 10 февраля 2020

Мы знаем, что Маркеры получают из файла JSON, поэтому нам нужно преобразовать строку в двойное число: вот решение:

<ScrollView
          style={styles.placesContainer}
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false} 
          onMomentumScrollEnd={e => {
            const locations =
              e.nativeEvent.contentOffset.x > 0
                ? e.nativeEvent.contentOffset.x / Dimensions.get('window').width
                : 0;

            const { latitude, longitude, mark } = this.state.locations[locations];

            this.mapView.animateToCoordinate( 
              {
                latitude: JSON.parse(latitude), <-- Here
                longitude: JSON.parse(longitude) <-- Here
              }, 
              500
            );

            setTimeout(() => {
              mark.showCallout();
            }, 500);
          }}>
          {locations.map(locations => (
            <View key={locations.id} style={styles.place}>
              <Text style={styles.title}>Ponto {locations.id} </Text> 

              <Text style={styles.description}>Hora: {locations.hora}</Text>
              <TouchableOpacity
                style={styles.buttonStyle}
                onPress={this._toastWithDurationGravityOffsetHandler}>
                <Text> Próximo Ponto</Text>
              </TouchableOpacity>
            </View>
          ))}
        </ScrollView>
...