When attempting to retrieve the current position using "position.coords.latitude", I receive an undefined value

Having recently started with Ionic2, I came across a helpful tutorial that worked flawlessly for me. The tutorial, which can be found at , demonstrates listing nearby places and calculating the distance between these locations and a hardcoded place in the code. My goal was to use the device's current location instead of the predefined one in the code. Here is a screenshot showing my progress so far: view screenshot of my application. Additionally, here is the code snippet from my locations provider:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import {Geolocation} from '@ionic-native/geolocation';

/*
Generated class for the LocationsProvider provider.

See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class LocationsProvider {

data: any;
Currentlatitude: any;
Currentlongitude: any;


constructor(public http: Http, public geolocation: Geolocation) {
console.log('Hello LocationsProvider Provider'); 
}

load(){     
this.geolocation.watchPosition().subscribe((position) => {
this.Currentlatitude = position.coords.latitude;
this.Currentlongitude = position.coords.longitude;                 
});

if(this.data){
return Promise.resolve(this.data);
}

return new Promise(resolve => {     
this.http.get('assets/data/locations.json').map(res => res.json()).subscribe(data => {     
this.data = this.applyHaversine(data.locations);     
this.data.sort((locationA, locationB) => {
return locationA.distance - locationB.distance;
});     
resolve(this.data);
});     
});     
}

applyHaversine(locations){
// this must change according to the device location
/*

let usersLocation = {
lat: 40.713744, 
lng: -74.009056
};  */

console.log("this.Currentlatitude ",this.Currentlatitude);

let usersLocation = {
latitude: this.Currentlatitude,
longitude: this.Currentlongitude
};

console.log("usersLocation.latitude ",usersLocation.latitude);
locations.map((location) => {
let placeLocation = {
latitude: location.latitude,
longitude: location.longitude
};

location.distance = this.getDistanceBetweenPoints(usersLocation, placeLocation, 'km').toFixed(2);               
});

return locations;
}

getDistanceBetweenPoints(start, end, units){     
let earthRadius = {
miles: 3958.8,
km: 6371
};

let R = earthRadius[units || 'km'];

let lat1 = start.latitude;

let lon1 = start.longitude;

let lat2 = end.latitude;

let lon2 = end.longitude;
console.log("lon1 ",lat1); // here it gives me undefined

let dLat = this.toRad((lat2 - lat1));

let dLon = this.toRad((lon2 - lon1));

let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);

let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let d = R * c;

return d;     
}

toRad(x){            
return x * Math.PI / 180;
}     
}

Answer №1

Recently, I developed a location service for my application. I utilized the geolocation plugin to retrieve my current location and the distancematrix API from Google Maps to calculate the distance/time between two addresses (coordinates or regular addresses).

import { Query } from '../models/query';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Geolocation, Geoposition, Coordinates } from '@ionic-native/geolocation';
import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult } from '@ionic-native/native-geocoder';

@Injectable()
export class LocationService {

  google_API_KEY: string = 'API_KEY_FROM_GOOGLE_GOES_HERE';
  currentLocation: Geoposition;

  constructor(public http: Http, private geolocation: Geolocation,
    private geocoder: NativeGeocoder) {
    // Define your current location here, or manually set it throughout the application
    this.setCurrentLocation();
  }


  setCurrentLocation() {
    return this.geolocation.getCurrentPosition().then((resp) => {
      // Modify resp if necessary
      this.currentLocation = resp;
      console.log(JSON.stringify(this.currentLocation));
    }).catch((error) => {
      console.log('Error obtaining location', error);
    })
  }

  getBetweenCoordsDetails(fromString: string, toString: string) {
    let query = new Query('https://maps.googleapis.com/maps/api/distancematrix/json');
    query.add('key', this.google_API_KEY);
    query.add('destinations', toString);
    query.add('origins', fromString);
    query.add('units', 'imperial');
    return this.http.get(query.toQuery())
      .do(resp => {
        let x = resp;
      }, error => {
        let x = error;
      })

  }

  getBetweenCoordAndHereDetails(toString: string) {
    let x = this.currentLocation.coords;
    return this.getBetweenCoordsDetails(this.currentLocation.coords.latitude + ',' + this.currentLocation.coords.longitude, toString);
  }

  getCoordinatesFromAddress(address: string) {
    return this.geocoder.forwardGeocode(address);
  }

}

Answer №2

After some trial and error, I realized that my struggle stemmed from a lack of understanding about synchronous and asynchronous tasks when using Promises and Observables in Ionic. For anyone facing the same challenge, I recommend checking out this helpful tutorial that delves into this topic: . Regarding the resolution to my issue, I stumbled upon the answer within this post: Get current position in ionic2

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage the useParams data to serve as a state object key in the useSelector function using TypeScript

Looking to access state data using a key obtained from useParams? Here's an example: export const MainPageSection = (props:MainPageSectionPropsType) => { const params = useParams(); const currentSection = params.section const excursions ...

Do not include the "dist" folder when exporting sub-modules in TypeScript

I've developed a basic module called modA: modA/ - package.json - dist/ - index.js - db.js - stuff.js My goal is to use the submodules "db" and "stuff" like this: import * as db from modA/db -- how can I achieve this? My package.json has main: ...

Exploring Typescript's type narrowing capabilities through destructuring

This code snippet is encountering errors: type Example = { x: true, y: null, z: null } | { x: false, y: Error, z: null } | { x: false, y: null, z: { val: number} } function getExample(): Example { return { x: false, y: null, z: { val ...

Can undefined be forcibly assigned with strict null checks enabled?

Considering enabling the strictNullChecks flag for a TypeScript project I've been developing leads to numerous compiler errors. While some of these errors are relevant edge cases, many follow a specific pattern. type BusinessObject = { id: string; ...

Utilizing Angular 2's NgFor directive in SVG Elements

I want to use ngFor to draw an SVG Element that consists of lines. I am struggling with the implementation and need some help fixing the code. Here is what I have so far: my-component.js: import {Component} from 'angular2/core'; @Component({ ...

Filter and transfer data from one Angular array to another

As a newcomer to Angular, I am working with an array of events containing multiple arguments. My goal is to filter these events and separate them into two new arrays: upcoming events and past events. Below is a snippet of the TypeScript code I am using: a ...

What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally. Below is the code snippet: Base.vue <templa ...

Using TypeScript's Array Union Type in defining function parameters

My scenario involves a union type of an Array with specific lengths: [ number ] | [ number, number ] | [ number, number, number, number ] The requirements are for an array with either one element, two elements, or four elements. I am attempting to create ...

Should I opt for the spread operator [...] or Array.from in Typescript?

After exploring TypeScript, I encountered an issue while creating a shorthand for querySelectorAll() export function selectAll(DOMElement: string, parent = document): Array<HTMLElement> | null { return [...parent.querySelectorAll(DOMElement)]; } ...

Using Typescript in combination with snowpack may result in nullish coalescing operators being generated when targeting a version lower than ES2020

I've been working on compiling my TypeScript code/packages to ensure compatibility with Safari Version less than 14. After researching, I discovered that nullish coalescing operators (??) are not allowed in the targeted version. Despite changing my t ...

When you hover over the button, it seamlessly transitions to a

Previously, my button component was styled like this and it functioned properly: <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 ...

Utilizing Ag-Grid's clipboard feature with the community version

Recently, I encountered a task that required me to transfer multiple rows of data from an Excel sheet into the ag-grid. After some research, I found out that this functionality is only available in the Enterprise version of the grid. However, I am intere ...

TypeScript throws an error if trying to access an Object variable using a String

While the code below is functioning as intended, I am encountering an error in the VS Code Typescript compiler stating that "Type 'String' cannot be used as an index type". Oddly enough, using a string literal instead of a variable like ...

Oops! There seems to be a hiccup: Unable to locate the control with the specified path: 'emails -> 0 -> email'

I am attempting to design a form incorporating a structure like this: formGroup formControl formControl formArray formGroup formControl formControl However, upon clicking the button to add reactive fields and submitting the form ...

Displaying numerical values in data labels for a donut chart using Highcharts

Currently, I have a donut highchart displaying names in the data labels. However, I need to show numbers instead. Can someone guide me on how to achieve this? This is my angular typescript code for the donut highchart: import { Component, OnInit, Input, ...

How to Send Data with NodeJS by Utilizing the Finish Event

Is there a way to retrieve the JSON data sent during the nodejs finish event? This is how I send the JSON data: oResponse.json({ version: "1.0.0", author: "Someone", contributors: "also Someone" }); I would like ...

Guide to swapping out embedded objects within a TypeScript data structure

I am in need of modifying a TypeScript object by conducting a key search. It is important to note that the key may be repeated within the object, so I must ensure it belongs to the correct branch before making modifications to the corresponding object. To ...

The functionality of ngModel is not functioning properly on a modal page within Ionic version 6

Currently I am working on an Ionic/Angular application and I have encountered a situation where I am attempting to utilize ngModel. Essentially, I am trying to implement the following functionality within my app: <ion-list> <ion-item> <ion ...

Programmatically populating the date picker in angular material

I have implemented the Angular Material date picker in one of the components of my Angular project. This specific component consists of two tabs, and I am using *ngIf to display only one tab at a time based on user interaction. When a user selects a date i ...

What is the process of importing types in TypeScript?

Here is the export I am working with: import * as jwt from 'jsonwebtoken'; ... export type MyJsonWebToken = typeof jwt; Next, when attempting to use it in my code: export class AuthService { constructor( @Inject(constants.JWT) private ...