9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

react-nativeで現在地取得した時に、現在地を中心にしたい

Posted at

はじめに

react-nativeで現在地取得アプリを作ることはできた。
しかし、ずれたところで、再度、現在位置を取得しても、現在地が中心に来ない

なんとかして、中心に現在地を表示させたい。

コード

App.js
import React,{Component}from 'react';
import {
  StyleSheet,
  Text,
  View,
  Platform,
  TouchableOpacity,
  Image,
} from 'react-native';

import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import MapView from 'react-native-maps';
// import { AssertionError } from 'assert';

const STATUS_BAR_HEIGHT = Platform.OS == 'ios' ? 20 : statusbar.currentHeight;

export default class App extends Component{
  constructor(props){
    super(props)
    this.state ={
      latitude:null,
      longitude:null,
      message:'位置情報取得中',
    }
  }
  componentDidMount(){
    this.getLocationAsync()
  }
  getLocationAsync = async() =>{
    console.log('現在位置取得中')
    const {status} = await Permissions.askAsync(Permissions.LOCATION)
    if(status !== 'granted'){
      this.setState({
        message:'位置情報のパーミッションの取得に失敗しました。'
      })
      return
    }
    const location = await Location.getCurrentPositionAsync({});
    this.setState({
      latitude:location.coords.latitude,
      longitude:location.coords.longitude,
    })

  }
  render(){
    if(this.state.latitude && this.state.longitude){
      return (
        <View style={styles.container}>
          <MapView
            style={{flex:1}}
            initialRegion={{
              latitude:this.state.latitude,
              longitude:this.state.longitude,
              latitudeDelta:0.002,
              longitudeDelta:0.002,
            }}
            showsUserLocation={true}
          />
          <TouchableOpacity onPress={this.getLocationAsync}style={styles.now}>
            {/* <Text>現在地取得</Text> */}
            <Image 
              resizeMode='contain'
              source={require(`./assets/location.png`)} 
              style={{width:20,height:20,transform: [{ rotate: '340deg' }], }}
              />
          </TouchableOpacity>
          
        </View>
      );
    }
    return (
      <View style={{flex:1,justifyContent:"center"}}>
        <Text>{this.state.message}</Text>
        
      </View>
      )

  }
}

const styles = StyleSheet.create({
  container:{
    paddingTop:STATUS_BAR_HEIGHT,
    flex:1,
    backgroundColor:'#fff',
    justifyContent:'center',
  },
  now:{
    position:'absolute',
    right:10,
    top:30,
  }
})

解決

App.js
import React,{Component}from 'react';
import {
  StyleSheet,
  Text,
  View,
  Platform,
  TouchableOpacity,
  Image,
} from 'react-native';

import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import MapView from 'react-native-maps';
// import { AssertionError } from 'assert';

const STATUS_BAR_HEIGHT = Platform.OS == 'ios' ? 20 : statusbar.currentHeight;

export default class App extends Component{
  constructor(props){
    super(props)
    this.state ={
      latitude:null,
      longitude:null,
      message:'位置情報取得中',
    }
  }
  componentDidMount(){
    this.getLocationAsync()
  }
  getLocationAsync = async() =>{
    console.log('現在位置取得中')
    const {status} = await Permissions.askAsync(Permissions.LOCATION)
    if(status !== 'granted'){
      this.setState({
        message:'位置情報のパーミッションの取得に失敗しました。'
      })
      return
    }
    const location = await Location.getCurrentPositionAsync({});
    this.setState({
      latitude:location.coords.latitude,
      longitude:location.coords.longitude,
    })

  }
  render(){
    if(this.state.latitude && this.state.longitude){
      return (
        <View style={styles.container}>
          <MapView
            style={{flex:1}}
            initialRegion={{
              latitude:this.state.latitude,
              longitude:this.state.longitude,
              latitudeDelta:0.002,
              longitudeDelta:0.002,
            }}
            region={{
              latitude:this.state.latitude,
              longitude:this.state.longitude,
              latitudeDelta:0.002,
              longitudeDelta:0.002,

            }}
            showsUserLocation={true}
          />
          <TouchableOpacity onPress={this.getLocationAsync}style={styles.now}>
            {/* <Text>現在地取得</Text> */}
            <Image 
              resizeMode='contain'
              source={require(`./assets/location.png`)} 
              style={{width:20,height:20,transform: [{ rotate: '340deg' }], }}
              />
          </TouchableOpacity>
          
        </View>
      );
    }
    return (
      <View style={{flex:1,justifyContent:"center"}}>
        <Text>{this.state.message}</Text>
        
      </View>
      )

  }
}

const styles = StyleSheet.create({
  container:{
    paddingTop:STATUS_BAR_HEIGHT,
    flex:1,
    backgroundColor:'#fff',
    justifyContent:'center',
  },
  now:{
    position:'absolute',
    right:10,
    top:30,
  }
})

追加したコード

MapViewの所に

region={{
  latitude:this.state.latitude,
  longitude:this.state.longitude,
  latitudeDelta:0.002,
  longitudeDelta:0.002,
}}

を加えたら、現在地取得するたびに、現在地を中心とした地図を表示することができた。
これで、解決。

9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?