Как установить увеличение при выборе маркера на карте? - PullRequest
0 голосов
/ 18 февраля 2020

Как установить масштаб только для маркера, выбранного на карте, а не для сфокусированного местоположения? вот мой код: я перепробовал много кодов, но пока не добился успеха.

export default class Mapper extends Component {
  constructor(props) {
    super(props);
    this.state = {
      focusedLocation: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta:
          (Dimensions.get('window').width / Dimensions.get('window').height) *
         0.00522,
      },
      locations: locations,
    };
    this.switchMapType = this.switchMapType.bind(this);
  }

  onPressZoomIn() {
    this.region = {
      latitude: this.state.focusedLocation.latitude,
      longitude: this.state.focusedLocation.longitude,
      latitudeDelta: this.state.focusedLocation.latitudeDelta * 0.5,
      longitudeDelta: this.state.focusedLocation.longitudeDelta * 0.5,
    };

    this.setState({
      focusedLocation: {
        latitudeDelta: this.region.latitudeDelta,
        longitudeDelta: this.region.longitudeDelta,
        latitude: this.region.latitude,
        longitude: this.region.longitude,
      },
    });
    this.map.animateToRegion(this.region, 500);
  }

  onPressZoomOut() {
    this.region = {
      latitude: this.state.focusedLocation.latitude,
      longitude: this.state.focusedLocation.longitude,
      latitudeDelta: this.state.focusedLocation.latitudeDelta / 0.5,
      longitudeDelta: this.state.focusedLocation.longitudeDelta / 0.5,
    };
    this.setState({
      focusedLocation: {
        latitudeDelta: this.region.latitudeDelta,
        longitudeDelta: this.region.longitudeDelta,
        latitude: this.region.latitude,
        longitude: this.region.longitude,
      },
    });
    this.map.animateToRegion(this.region, 500); 
  }
  render() {
    return (
      <View style={styles.container}>
       <StatusBar hidden />
        <MapView
          //initialRegion={initialRegion}
          style={styles.mapView}
          rotateEnabled={true}
          scrollEnabled={true}
          showsMyLocationButton={false}
          showsUserLocation={true}
          zoomEnabled={true}
          mapType={this.state.mapType}
          showsPointsOfInterest={false}
          showBuildings={false}
          onMapReady={this._mapReady}
          ref={ref => (this.map = ref)}>
          {locations.map(
            (locations, id, latitude, longitude, hora, linha, prestadora) => (
              console.log(locations.latitude, locations.latitude),
              (
                <MapView.Marker
                  onPress={this.pickLocationHandler}
                  ref={mark => (locations.mark = mark)}
                  key={id}
                  title={locations.linha + ' - ' + locations.prestadora}
                  pinColor={'tomato'}
                  description={
                    'Aguarde o seu transporte a partir de: ' + locations.hora
                  }
                  coordinate={{
                    latitude: JSON.parse(locations.latitude),
                    longitude: JSON.parse(locations.longitude),
                  }}
                />
              )
            )
          )}
        </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.map.animateToCoordinate(
              {
                latitude: JSON.parse(latitude),
                longitude: JSON.parse(longitude),
              },
              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.text}>A partir de: {locations.hora}</Text>
              <Image
                source={require('./assets/expo.symbol.white.png')}
                style={{
                  marginLeft: Dimensions.get('window').width / 1.5,
                  width: 67,
                  height: 67,
                  tintColor: '#FF3D00',
                }}
              />
            </View>
          ))}
        </ScrollView>
      </View>
    );
  }
}

Как это исправить? например, когда я нажимаю кнопку увеличения, требуется увеличение выбранного маркера c?

Вот полный код для просмотра: https://snack.expo.io/@matheus_cbrl / zoomin-zoomout

вот код для выбора местоположения по маркеру обработчика:

pickLocationHandler = event => {
    const coords = event.nativeEvent.coordinate;
    console.log('Location picker Marker', coords);
    this.map.animateToRegion({
      ...this.state.focusedlocation,
      latitude: coords.latitude,
      longitude: coords.longitude,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta:
          (Dimensions.get('window').width / Dimensions.get('window').height) *
          0.00522,
    });

    this.setState(prevState => {
      return {
        focusedlocation: {
          ...prevState.focusedlocation,
          latitude: coords.latitude,
          longitude: coords.longitude,
        },
        locationChosen: true,
      };
    });
  };

Ответы [ 2 ]

1 голос
/ 18 февраля 2020

Сначала перейдите к маркеру, затем увеличьте.

Переместите к маркеру,

this.refs.map.animateToRegion({
     latitude: markerLat,
     longitude: markerLong,
})

Затем увеличьте с помощью focusedLocation.

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

Я нашел решение:

Первый:

  _mapReady = () => {
    this.state.locations[0].mark.showCallout();
    this.animate(); <---ADD THIS METHOD
  };

Второй Создайте эту функцию, анимируя к первой точке вашего интереса ...

  animate(){
    let r = {
        latitude: JSON.parse(this.state.locations[0].latitude),
        longitude: JSON.parse(this.state.locations[0].longitude),
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta:
        (Dimensions.get('window').width / Dimensions.get('window').height) *
        0.00522,
    }; 
    this.map.animateToRegion(r, 500);
}

этот код произведет увеличение первого интересующего вас маркера .. проверьте !!

...