反应原生地图。区域更改完成后,Google地图会返回初始位置

时间:2018-04-11 15:51:26

标签: react-native google-maps-markers

我希望在地图上列出带有标记的注册用户,他/她可以看到附近的应用用户。地图显示了初始标记,但除了地图插入其初始位置之外,我看不到动态分配的标记。例如,当我完成拖动地图后,我将地图拖动到其他位置,然后返回。

App.js

import React, { Component } from 'react';
import { Text, View, StyleSheet, Switch, Alert, AppRegistry } from 'react-native';
import MapView from 'react-native-maps';
import Fetchdata from './Fetchdata.js';

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    height: 400,
    width: 400,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});

export default class Stage extends Component {
  render() {
    return (
      <View style ={styles.container}>
        <Fetchdata />
      </View>
    );
  }
}

FetchData.js

import React, { Component } from 'react'
import { Text, View, StyleSheet, Switch, Alert, AppRegistry} from 'react-native'
import MapView, {Marker} from 'react-native-maps';

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    height: 400,
    width: 400,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});
export default class Fetchdata extends Component {
  constructor (props) {
    super(props);
  }
  state = {
      latitude: 3.148561,
      longitude: 101.652778,
      markers: [{
    title: 'hello',
    coordinates: {
      latitude: 3.148561,
      longitude: 101.652778
    },
      },
      {
    title: 'hello',
    coordinates: {
      latitude: 3.149771,
      longitude: 101.655449
    },
      }]
   };
   componentDidMount = () => {
     navigator.geolocation.getCurrentPosition(
      (position) => {
    this.setState({
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      error: null,
    });

      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    );
   }
   onRegionChange (region) {
     fetch('https://isg.info.tr/query_maps.php' + '?latitude=' + this.state.latitude + '&longitude=' + this.state.longitude , {
    method: 'GET'
     })
     .then((response) => response.json())
     .then((responseJson) => {
       const newState = Object.assign({}, this.state);
       newState.markers.coordinates = responseJson;
       this.setState(newState);
       //Alert.alert(responseJson+ " ")
      //Alert.alert('https://isg.info.tr/query_maps.php' + '?latitude=' + this.state.latitude + '&longitude=' + this.state.longitude);
       //this.markers = responseJson;
    console.log(responseJson);
     })
     .catch((error) => {
    console.error(error);
     });
     //Alert.alert(responseJson);
   };
   render() {
      return (
      <View style={styles.container}>
      <MapView
      style={styles.map}
      region={{
        latitude: this.state.latitude,
        longitude: this.state.longitude,
        latitudeDelta: 0.015,
        longitudeDelta: 0.015,
      }}
      onRegionChangeComplete={this.onRegionChange.bind(this)}
      >
      {this.state.markers.map((marker, index) => (
        <MapView.Marker key={index} coordinate={marker.coordinates} title={marker.title} />
      ))}
    </MapView>
      </View>
      );
   }
}

来自主服务器上的查询的Json文件

[{"latitude" : 40.3565,"longitude" : 27.9774},{"latitude" : 40.3471,"longitude" : 27.9598},{"latitude" : 40,"longitude" : 27.9708}]

2 个答案:

答案 0 :(得分:1)

您正在onRegionChange制作州的副本。这包括this.state.latitudethis.state.longitude,当您setState来电后执行fetch时,setStatestate根本不会更新。因此,一旦region执行,地图将会快速恢复&#34;到最后保存在state中的内容。

解决此问题的一种方法是使用传递给onRegionChange的内容(使用您的编码样式)更新.then((responseJson) => { const newState = Object.assign({}, this.state); newState.markers.coordinates = responseJson; newState.latitude = region.latitude; newState.longitude = region.longitude; this.setState(newState); console.log(responseJson); }) 受控state值:

region

或者,如果您依赖于在您的其他位置拥有最新的latitude信息(longitudefetch),请先更新setState的该部分内容码。然后拨打onRegionChange (region) { this.setState({ latitude: region.latitude, longitude: region.longitude, }, () => { fetch('https://isg.info.tr/query_maps.php' + '?latitude=' + // ...the rest of your fetch call code here as is... }); }; 回调中的state

state

如果我们这样,我就不会批量复制你的state。它在React中不是一种非常普通的做法,在处理markers中的大量数据时效率很低。相反,我可能会选择仅更新需要更新的.then((responseJson) => { let markers = [...this.state.markers]; markers.coordinates = responseJson; this.setState({ markers }); console.log(responseJson); }) 部分(latitude):

longitude

请注意,我没有更新state中存储的MapViewregion值,因为region如果设置initialRegion就可以正常工作{{} 1}}一次然后永远不会更新它使用的值。但是,如果这是您的使用案例而您并不打算控制The Smart card resource manager is not running,我建议您使用public class Program { public static void Main() { var factory = DeviceMonitorFactory.Instance; var subscription = factory .CreateObservable(SCardScope.System) .Subscribe(OnNext, OnError); Console.ReadKey(); subscription.Dispose(); } private static void OnError(Exception exception) { Console.WriteLine($"{DateTime.Now} ERROR: {exception.Message}"); } private static void OnNext(DeviceMonitorEvent ev) { Console.WriteLine($"{DateTime.Now} Event type {ev.GetType()}, (readers: {string.Join(", ", ev.Readers)})"); } } 道具。这将导致将来更少的错误。

答案 1 :(得分:0)

尝试此操作,将标记放在地图中心,当用户移动地图时,使用onRegionChangeComplete获取最后的位置。您可以从此链接阅读概念

https://alizahid.dev/blog/keep-marker-in-center-and-move-map-around-it