Android, can I pull address in parts?


#1

Hello,
I am not an ionic dev but I have worked with native and I am running into a problem on a project I have to manage. The developer is saying that on android, you can’t get the address from a phone contact in parts only as one string. Meaning, I can only fetch “123 main, city, ST, zip”, rather than say a json string that has “street”:“123main”, “City”:“city”… etc…

I have googled it and I can see plenty of examples of how to get an address but I am not finding one that shows the result I can expect.

Could someone tell me if that is true that ionic only lets me fetch an address string and not in parts? Even more amazing, maybe even tell me how the return looks or paste in an example?

Thank you for your time!


#2

Ionic itself doesn’t handle addresses and contacts at all, only via a Cordova plugin. Probably https://github.com/apache/cordova-plugin-contacts via https://ionicframework.com/docs/native/contacts/ There you can find documentation how the result will look like: https://ionicframework.com/docs/native/contacts/#IContactAddress or https://github.com/apache/cordova-plugin-contacts#contactaddress


#3

You can (probably) get the result you want using ionic-native Geocoder.
import to page

import { NativeGeocoder, NativeGeocoderForwardResult, NativeGeocoderReverseResult } from '@ionic-native/native-geocoder’;

interface Location {
latitude: number,
longitude: number
}

export class ContactPage {
location: Location;

in constructor

constructor(nativeGeo: NativeGeocoder){
this.location = {
latitude: 0,
longitude: 0
  }
}

in Component: something like this

getCoordinates(): Promise<void> {
    return this.nativeGeo.forwardGeocode( contactAddress)
    .then(( result: NativeGeocoderForwardResult ) => {
     this.location.latitude = parseFloat(result.latitude);
     this.location.longitude = parseFloat(result.longitude);
     })
  }

reverseGeocode(): Promise<void> {
  return this.nativeGeo.reverseGeocode(this.location.latitude, this.location.longitude)
  .then((result: NativeGeocoderReverseResult ) => {
    console.log(JSON.stringify(result))
   }
}

For your purposes, you can / should probably remove the Promise<void> tags and return from the functions. I have them in there as they are part of a larger function that is already in a working component

This is what the result looks like (modified)

  {"subAdministrativeArea":"Williamson","postalCode":"37069","locality":"Franklin",
   "subLocality":"Southeast","subThoroughfare":"2434","administrativeArea":"TN",
   "countryName":"United States","countryCode":"US","thoroughfare":"Anston Lane"}