Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

React-Native-maps How do I keep updating regions in MapView?

I implemented a function that moves the marker's number to that location when it is found on the search screen. And I want to print only certain markers when I press the button(Button.showSpecificMarker) on MainScreen.

However, when I press the button, only certain markers are printed, but it moves to the last searched region, not the region I'm looking at.

MainScreen.js

import { StyleSheet, Image, View, Text, TouchableOpacity, Button } from 'react-native';
import { Icon } from 'native-base'; // ??? ??
import { withNavigation, navigation } from 'react-navigation';
import MapView, { Marker, PROVIDER_GOOGLE, MAP_TYPES } from 'react-native-maps';
import iksonData from './ikson.json';

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: 'white' },
  text: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  iconImg: {
    width: 30,
    height: 30,
    padding: 10,
    marginLeft: 5,
  }
});

function MapScreen(props) {
  const [region, setRegion] = useState({
    latitude: 35.962691,
    longitude: 126.97894,
    latitudeDelta: 0.0322,
    longitudeDelta: 0.0321,
  });
  const [findRegion, setFindRegion] = useState({
    latitude: null,
    longitude: null,
    latitudeDelta: null,
    longitudeDelta: null,
  });
  const [showVehicleReader, setShowVehicleReader] = useState(-1);
  const [btnTitle, setBtnTitle] = useState('??? ???? ??');
  const new_region = props.navigation.getParam('region');
  let markers;

  const handleBtnPress = () => {
    setShowVehicleReader((showVehicleReader === -1) ? 0 : -1);
    setBtnTitle((btnTitle === '??? ???? ??') ? '?? ??' : '??? ???? ??');
  }

  //  -1? ?? 0? ??? ????, 1? ??? ??? ??
  if (showVehicleReader === 1) {
    markers = <View>
      {iksonData.map((item) =>
        (item.purpose !== '???????') ?
          <Marker
            key={item.id}
            title={item.id + "? CCTV"}
            description={item.lotAddress}
            coordinate={{
              latitude: parseFloat(item.latitude),
              longitude: parseFloat(item.longitude),
            }}
          />
          :
          null
      )}
    </View>
  } else if (showVehicleReader === 0) {
    markers = <View>
      {iksonData.map((item) =>
        (item.purpose === '???????') ?
          <Marker
            key={item.id}
            title={item.id + "? CCTV"}
            description={item.lotAddress}
            coordinate={{
              latitude: parseFloat(item.latitude),
              longitude: parseFloat(item.longitude),
            }}
            pinColor={'blue'}
          />
          :
          null
      )}
    </View>
  } else {
    markers = <View>
      {iksonData.map((item) =>
        (item.purpose === '???????') ?
          <Marker
            key={item.id}
            title={item.id + "? CCTV"}
            description={item.lotAddress}
            coordinate={{
              latitude: parseFloat(item.latitude),
              longitude: parseFloat(item.longitude),
            }}
            pinColor={'blue'}
          />
          :
          <Marker
            key={item.id}
            title={item.id + "? CCTV"}
            description={item.lotAddress}
            coordinate={{
              latitude: parseFloat(item.latitude),
              longitude: parseFloat(item.longitude),
            }}
          />
      )}
    </View>
  }

  //rendering!!!
  return (
    <View style={styles.container}>
      <MapView
        style={{ flex: 1 }}
        zoomEnabled={true}
        provider={PROVIDER_GOOGLE}
        mapType="hybrid"
        minZoomLevel={13}
        maxZoomLevel={19}
        initialRegion={
          {
            latitude: 35.962691,
            longitude: 126.97894,
            latitudeDelta: 0.0322,
            longitudeDelta: 0.0321,
          }
        }

        region={new_region || region}
      >
        {markers}
      </MapView>
      <View>
        <Button
          class='showSpecificMarker'
          title={btnTitle}
          color="#f194ff"
          onPress={handleBtnPress}
        />
      </View>
    </View>
  );
}

// navigationOptions ?? ??
MapScreen.navigationOptions = ({ navigation }) => {
  return {
    headerLeft: () => <Image source={require('./assets/logo.jpg')} style={styles.iconImg} />,
    title: <Text style={styles.text}>9585?? CSMap</Text>,
    headerRight: () =>
    (
      <TouchableOpacity onPress={() => navigation.navigate('Search')}>
        <Icon name='ios-search' style={{ paddingRight: 10 }} />
      </TouchableOpacity>
    ),
    headerTitleAlign: 'center',
  }
}

export default withNavigation(MapScreen);

SearchScreen.js

// https://aboutreact.com/react-native-search-bar-filter-on-listview/
// import React in our code
import React, { useState, useEffect } from 'react';

// import all the components we are going to use
import { SafeAreaView, Text, StyleSheet, View, FlatList, TouchableOpacity } from 'react-native';
import { SearchBar } from 'react-native-elements';
// ?? ???
import iksonData from './ikson.json';

const SearchScreen = (props) => {
  const { navigation, route } = props;
  const [search, setSearch] = useState('');
  //filter?? ? ??? ???
  const [filteredDataSource, setFilteredDataSource] = useState([]);
  // ???? ???? ? ????? ?? ???
  const [masterDataSource, setMasterDataSource] = useState([]);

  useEffect(() => {
    setFilteredDataSource(iksonData);
    setMasterDataSource(iksonData);
  }, []);

  const searchFilterFunction = (text) => {
    // Check if searched text is not blank
    if (text) {
      // Inserted text is not blank
      // Filter the masterDataSource
      // Update FilteredDataSource
      const newData = masterDataSource.filter(function (item) { //CCTV ??? ??? ??
        const itemData = String(item.id);
        const textData = text;
        return itemData.indexOf(textData) > -1;
      });
      setFilteredDataSource(newData);
      setSearch(text);
    } else {
      // Inserted text is blank
      // Update FilteredDataSource with masterDataSource
      setFilteredDataSource(masterDataSource);
      setSearch(text);
    }
  };

  // flatlist item ??
  const ItemView = ({ item }) => {
    return (
      // Flat List Item
      <Text style={styles.itemStyle} onPress={() => getItem(item)}>
        <View style={{ flex: 1}}>
            <Text style={{ fontWeight: "bold", paddingTop: 25}}>{item.id + "? CCTV"}</Text>
            <Text style={{ paddingTop: 5}}>{'??: ' + item.lotAddress}</Text>
            <Text style={{ paddingTop: 5}}>{'??: ' + item.purpose}</Text>
        </View>
      </Text>
    );
  };

  const ItemSeparatorView = () => {
    return (
      // Flat List Item Separator
      <View
        style={{
          height: 0.5,
          width: '100%',
          backgroundColor: '#C8C8C8',
        }}
      />
    );
  };

  const getItem = (item) => {
    navigation.navigate('Main', {
      region:{
        latitude:item.latitude,
        longitude:item.longitude,
        latitudeDelta: 0.0022,
        longitudeDelta: 0.0021,
      }
    })
  };


  // flatlist? data? ????
  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={styles.container}>
        <SearchBar
          round
          searchIcon={{ size: 24 }}
          onChangeText={(text) => searchFilterFunction(text)}
          onClear={(text) => searchFilterFunction('')}
          placeholder="???? CCTV ??? ??????."
          value={search}
        />
        <FlatList
          data={filteredDataSource}
          keyExtractor={(item, index) => index.toString()}
          ItemSeparatorComponent={ItemSeparatorView}
          renderItem={ItemView}
        />
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
  },
  itemStyle: {
    padding: 10,
  },
});

export default SearchScreen;

I think it moves to the last place searched by the region={new_region||region} in MainScreen MapView. Then how can I press the button to get the region I'm watching now?

=======

Enter link video here

question from:https://stackoverflow.com/questions/65930005/react-native-maps-how-do-i-keep-updating-regions-in-mapview

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Hope you are doing good.

Here is the updating code you can try

componentDidMount() {
    this._getLocationAsync();
  }

  _getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
      this.setState({
        errorMessage: 'Permission to access location was denied',
      });
    }
    let location = await Location.getCurrentPositionAsync({});
    this.setState({ location });
    this.setState({
          region: {
            latitude: location.coords.latitude,
            longitude: location.coords.longitude,
            latitudeDelta: 0.003,
            longitudeDelta: 0.003,
          },
        });
      }



state = {
    location: null,
    region:null,
    errorMessage: null,
    marker: {latitude: 0,longitude: 0},
  };

      <MapView style={styles.map}
       showsUserLocation = {true}
       onRegionChange={this.onRegionChange.bind(this)}
       region={this.state.region} >
       <MapView.Marker
       coordinate={this.state.marker}
       title={"title"}
       description={"description"}/>
       </MapView>

Hope this helps , feel free to ask if you have any doubts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...