Geolocation - can't get latitude and longitude in React/Redux app

geolocation api
geolocation map
geolocation javascript
geolocation ip
geolocation example
geolocation finder
geolocation data
jquery geolocation

I have following action creator:

export const getLocation = () => {
    const geolocation = navigator.geolocation;

    const location = new Promise((resolve, reject) => {
        if (!geolocation) {
            reject(new Error('Not Supported'));
        }

    geolocation.getCurrentPosition((position) => {
        resolve(position);
    }, () => {
        reject (new Error('Permission denied'));
    });
  });

  return {
      type: GET_LOCATION,
      payload: location
  }
};

And following reducer for GET_LOCATION type:

case GET_LOCATION: {
          return {
              ...state,
              location: {
                  latitude: action.location.coords.latitude,
                  longitude: action.location.coords.latitude,

              }
          }
      }

I try to use this data in my component like so:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getLocation } from '../actions';
import { bindActionCreators } from 'redux';

class UserLocation extends Component {
     constructor(props) {
         super(props);
     }

     componentWillMount() {
         this.props.getLocation();
     }

     render() {
         return (
            <div>
                <div><span>latitude:</span>{this.props.location.latitude} 
            </div>
            <div><span>longitude:</span>{this.props.location.longitude} </div>
        </div>
    );
  }
}

const mapDispatchToProps = dispatch => {
    return bindActionCreators( { getLocation }, dispatch )
}

export default connect(null, mapDispatchToProps)(UserLocation);

But everytime when I load this component I get TypeError: Cannot read property 'latitude' of undefined

Can you please point me where I was wrong?

The geolocation data will be resolved asynchronously, and is not available the first time your component is rendered. You need to correctly handle the case where that data is not yet available, and there's several ways you can do that. Please see the article Watch Out for Undefined State for descriptions of how to handle data that is not available.

Using the Geolocation API, The Geolocation API is used to retrieve the user's location, so that it can for example be used to display  Geocoding is often related to Geolocation. It is a process of finding associated geographic coordinates (latitude and longitude) from other geographic data such as city or address. With geographic coordinates the features can be mapped and entered into Geographic Information Systems.

You should use componentWillReceiveProps to receive the returned data from dispatched action.

componentWillReceiveProps = (nextProps) => {
    if (this.props.location.latitude !== nextProps.location.latitude) {
      // You will have location object here that is returned from recuder
    }
  }

Check this alternative way to call geocoding to fetch lat and long in react with redux

https://medium.com/@eesh.t/auto-detect-location-react-component-using-google-geocoding-and-reverse-geocoding-in-autocomplete-66a269c59315

Geolocation, Geolocation. - REC. Method of informing a website of the user's geographical location. Usage % of. all users, all tracked  Geolocation can be used to determine time zone and exact positioning coordinates, such as for tracking wildlife or cargo shipments.

You're doing the request in componentWillMount() that it's before mount the component, but this doesn't not mean that the component will wait for the request end. Therefore you should put some validation in the render method like if(!this.props.location) return <div>Loading...</div>

How does geolocation work?, How Does an IP Address Give Away Your Location? How does geolocation work​? While it's true that your IP address  Internet and computer geolocation can be performed by associating a geographic location with the Internet Protocol (IP) address, RFID, hardware embedded article/production number, embedded software number (such as UUID, Exif/IPTC/XMP or modern steganography), invoice, Wi-Fi positioning system, device fingerprint, canvas fingerprinting or device GPS coordinates, or other, perhaps self-disclosed information.

I think I used too the example from the same Codepen as you, in it the author uses a very simplified version of a React Promise Middleware. But suggest that you use a redux-promise-middleware so you can control how the promise will be resolved.

So you should import the middleware and include it in applyMiddleware when creating the Redux store:

import promiseMiddleware from 'redux-promise-middleware'

composeStoreWithMiddleware = applyMiddleware(
  promiseMiddleware(),
)(createStore)

The promise that you're dispatching in your action creator must be handled in the reducer with a FULFILED promise suffix (there are another ways to do the same but you should be ok with this one, also I'm not a native English speaker, so watchout with typos in _FULFILLED).

case `${GET_LOCATION}_FULFILLED`:
  return {
    ...state,
    location: {
      latitude: action.location.coords.latitude,
      longitude: action.location.coords.latitude,
    }
  }

I use the location object from the render() method so you can use const mapStateToProps so you can use it from there.

const mapStateToProps = (state) => {
  return {location: state.location};
};

Then at the render method of your component you can destructure your location object from the props:

 render() {
   const { location: { latitude, longitude } } = this.props;
   return (
     <div>
       <div><span>latitude:</span>{latitude}</div>
       <div><span>longitude:</span>{longitude}</div>
     </div>
   );

Geolocation, IP address location data can include information such as country, region, city, postal/zip code, latitude, longitude and time  If your browser does not automatically start downloading our geolocation plugin, you may use the direct download links below: Windows users click here. Mac users click here.

Developer Guide | Geolocation API, A successful geolocation request will return a JSON-formatted response defining a location and radius. location : The  There are a several ways to find geolocation of a user: HTML5 API, Cell Signal and IP Address to name a few. Pairing of IP address to a geographical location is the method we used to provide geolocation data. There are times when you need to identify where your web visitors are coming from.

Geolocation API Usage and Billing, To manage your cost of use of the Google Maps Platform APIs, you can set daily quota limits on all requests to any  The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information. WebExtensions that wish to use the Geolocation object must add the "geolocation" permission to their manifest. The user's operating system will prompt the user to allow location access the first time it is requested.

What is Geolocation? How it Works & Why it Matters, Sometimes, a site will even display these little nuggets of Internet familiarity: “This website uses cookies  The HTML Geolocation API is used to get the geographical position of a user. Since this can compromise privacy, the position is not available unless the user approves it. Note: Geolocation is most accurate for devices with GPS, like smartphone.