R.Nish
R.Nish

Reputation: 73

Want to get current location from react native js+google api key

I want to get current location in text/alert in react native want city name in text

Here my code:

getData(){

        Geocoder.init("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

        Geocoder.from(41.89, 12.49)
            .then(json => {
                var addressComponent = json.results[0].formatted_address;
          console.log(addressComponent);
          console.log(addressComponent)
         alert(addressComponent);
            })
          .catch(error => console.warn(error));
        }

Upvotes: 1

Views: 4708

Answers (3)

R.Nish
R.Nish

Reputation: 73

getData(){

        Geocoder.init("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

        Geocoder.from(41.89, 12.49)
            .then(json => {
                var addressComponent = json.results[0].formatted_address;
          console.log(addressComponent);
          console.log(addressComponent)
         alert(addressComponent);
            })
          .catch(error => console.warn(error));
        }

I want to combine this with current location latitude n longitude

Upvotes: 2

hakki
hakki

Reputation: 6501

Complete example with Geolocation API.

As I said at comment; you don't need to Google API to get current coordinates of device. You can use Geolocation API

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class FindMyLocationExample extends Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      error: null,
    };
  }

  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: 10000, maximumAge: 1000 },
    );
  }

  render() {
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
    );
  }
}

Upvotes: 2

Saravana Kumar
Saravana Kumar

Reputation: 3396

Use this Code to get Current latitude and longitude:

navigator.geolocation.getCurrentPosition(
(position) => {
    console.log('lat',position.coords.latitude);
    console.log('lng',position.coords.longitude);
    //Your Code
    // ( DO fetch call to get address from lat and lng
    // https://maps.googleapis.com/maps/api/geocode/json?key= 
    <\API_KEY_HERE>&latlng="latitude","longitude"&sensor=true )
},
(error) => this.setState({ error: error.message }),
   { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);

Upvotes: 1

Related Questions