How do I use Reverse Geocoding?


#1

I’ve looked up Reverse Geocoding. For whatever reason the Native Geocoder does not work, even if I follow the documentation step-by-step, reset the project, or otherwise use other code.

What are some methods I can use to implement Reverse Geocoding on an Ionic v2 app? Nothing seems to work, or otherwise returns an empty promise. I don’t know if this is something that just hasn’t been updated in the docs, but nothing seems to be working here. Is there any code I can try?


#2

You are talking about https://ionicframework.com/docs/native/native-geocoder/?
What exactly did you implement?
What is your ionic info output?


#3

Here is what I implemented. As you can see, a lot of code is commented out from other geocoding methods I’ve tried to implement. I’ve tried a LOT of methods all of them returning nothing.

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { IdentifymytickPage } from '../identifymytick/identifymytick';
import { IdguidePage } from '../idguide/idguide';
import { RemovalPage } from '../removal/removal';
import { SymptomsPage } from '../symptoms/symptoms';
import { LoginPage } from '../login/login';
import { LocationAccuracy } from '@ionic-native/location-accuracy';
import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult } from '@ionic-native/native-geocoder';
import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 LatLng,
 CameraPosition,
 MarkerOptions,
 GeocoderRequest,
 GeocoderResult,
 Marker
} from '@ionic-native/google-maps';
import { Geocoder } from 'ionic-native';




@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

foo: string;
bar: string;
geotest:any;
location:any;
  constructor(public navCtrl: NavController, public geolocation: Geolocation, public locac: LocationAccuracy, private nativegeocoder: NativeGeocoder, public platform: Platform, private googleMaps: GoogleMaps) {



    //
    this.watch();
    this.getLocation();
    this.hideMe=false;
 //    this.platform.ready().then(() => {
 //
 //   nativegeocoder.reverseGeocode(52.5072095, 13.1452818)
 //     .then((result: NativeGeocoderReverseResult) => {
 //       this.foo = "The address is " + result.street + " " + result.houseNumber + " in " + result.city + ", " + result.countryCode;
 //       console.log("The address is " + result.street + " " + result.houseNumber + " in " + result.city + ", " + result.countryCode);
 //     })
 //     .catch((error: any) => console.log(error));
 //
 //   nativegeocoder.forwardGeocode("Berlin")
 //     .then((coordinates: NativeGeocoderForwardResult) => {
 //       this.bar = "The coordinates are latitude=" + coordinates.latitude + " and longitude=" + coordinates.longitude;
 //       console.log("The coordinates are latitude=" + coordinates.latitude + " and longitude=" + coordinates.longitude);
 //     })
 //     .catch((error: any) => console.log(error));
 // });

    console.log("confirming the constructor is running")


//     this.platform.ready().then(() => {
// console.log("confirming the function")
// this.geolocation.getCurrentPosition().then(
//   (resp) => {
//     console.log("Code passed into the geolocation")
//     let req = {
//       position: {
//         lat: resp.coords.latitude,
//         lng: resp.coords.longitude
//       }
//     }
//     console.log("Code passed through the geolocation and will go into the geocode")
//     // Определяем название города
//     Geocoder.geocode(req).then(
//       (res) => {
//         // do something
//         console.log("The code passed through the geocode!!!")
//         this.foo = res.countryName;
//       }
//     );
//   },
//   (err) => {
//   }
// );






    // this.nativeGeocoder.reverseGeocode(52.5072095, 13.1452818)
    //         .then((result:NativeGeocoderReverseResult) => {
    //           this.foo = "The address is " + result.street + " " + result.houseNumber + " in " + result.city + ", " + result.countryCode;
    //           console.log("The function ran on NativeGeocoder");
    //         })
    // .catch((error: any) => console.log("LOCATION ERROR:", error));
    // console.log("function ended")
// });

}

  nextPage()
  {
    this.navCtrl.push(IdentifymytickPage)
  }

  nextPage1()
  {
    this.navCtrl.push(IdguidePage)
  }

  nextPage2()
  {
    this.navCtrl.push(LoginPage)
  }

  nextPage3()
  {
    this.navCtrl.push(RemovalPage)
  }

  nextPage4()
  {
    this.navCtrl.push(SymptomsPage)
  }






coordslat:any;
coordslong:any;
accuracy:any;
error:any;

watch() {
  this.geolocation.getCurrentPosition().then((resp) => {
    this.coordslat = resp.coords.latitude;
    this.coordslong = resp.coords.longitude;
    this.accuracy = resp.coords.accuracy + ' meters';
    console.log("This Geolocation is running")
  }).catch((error) => {
    this.error = 'Error getting location: ' + error;
  })
}


getUserLocation() {
    // Определяем текущие координаты
        //   let req = {
        //     position: {
        //       lat: this.coordslat,
        //       lng: this.coordslong
        //     }
        //   }
        //   console.log("Code passed through the geolocation and will go into the geocode")
        //   // Определяем название города
        //   this.geocoder.geocode(req).then(
        //     (res) => {
        //       // do something
        //       console.log("The code passed through the geocode!!!")
        //       this.foo = res.countryName;
        //     }
        //   );
        // (err) => {
        // }

//         var request = {
//   lat: this.coordslat, lng: this.coordslong
// };
// geocode(request, function(results) {
//   if (results.length) {
//     var result = results[0];
//     var position = result.position;
//     var address = [
//       result.subThoroughfare || "",
//       result.thoroughfare || "",
//       result.locality || "",
//       result.adminArea || "",
//       result.postalCode || "",
//       result.country || ""].join(", ");
//
//     map.addMarker({
//       'position': position,
//       'title':  address
//     });
//   } else {
//     alert("Not found");
//   }
// });

  }

fullAddress:any;
addressString:string;
position:any;
  /*
    This function will get the location by using the native location option on the smartphone.
    It will return the current position from the latitude and longitude variables.
    The result will be : Address, City, Postal Code and Country.
    */
    private getLocation() {

      // Get the current latitude & longitude if the Location option is enable on the device
      this.geolocation.getCurrentPosition()
        .then((resp) => {
          this.position = {
            // Create latitude (lat) and longitude (lng) variables with the location informations
            lat: resp.coords.latitude,
            lng: resp.coords.longitude
          };

          this.nativegeocoder.reverseGeocode(this.position.lat, this.position.lng)
          .then((result: NativeGeocoderReverseResult) =>
          {
            // Put the result of the GeocoderReverse in the fullAddress variable
            this.fullAddress = result;
            // Put all the parameters in one
            this.addressString = result.street + ', ' + result.city + ' ' + result.postalCode + ', ' + result.countryName;
          })
          .catch((error: any) => alert(error));
        })
        .catch((error) => {
          alert('getLocation error\n' + JSON.stringify(error));
        })
    }

    hideMe:boolean;
    hide() {
      this.hideMe=true;
      document.getElementById("chgcolor").style.color = "white";
    }

//
// townvar:any;
//
// nearestCity() {
//
//   this.geolocation.getCurrentPosition().then((resp) => {
//     this.nativeGeocoder.reverseGeocode(resp.coords.latitude, resp.coords.longitude)
//       .then((result: NativeGeocoderReverseResult) => this.townvar = result.city)
//       .catch((error: any) => console.log(error));
//   })
//
// }

// geolocate() {
//   let options = {
//     enableHighAccuracy: true
//   };
//
//     this.geolocation.getCurrentPosition(options).then((position: Geoposition) => {
//     this.getcountry(position);
//
//   }).catch((err) => {
//     console.error(err);
//   })
//
// }
//
// getcountry(pos) {
//   this.geocoder.reverseGeocode(pos.coords.latitude, pos.coords.longitude).then((res: NativeGeocoderReverseResult) => {
//     console.log(res.countryName, res.city, res.district)
//
//   })
// }

geolocatetest() {

}

}

Ionic info returns:

"Gathering environment info - failed!
ReferenceError: xcode is not defined

Additionally, when I set an error alert on my android device, it returns a plugin_not_installed error. What could that mean?

Any help is greatly appreciated, thanks!


#4

Bumping this. Could really use some help on this.


#5

I would advise you to create a new, empty project (ionic start blank blank) and implement the exact example from the Ionic Native docs there. If this also doesn’t work, please upload the whole project to Github and share the link with us.


#6
  1. Could it be that you’re importing Geocoder a second time in your code?

  2. It may be the case that you have to add declare var google to your component. I haven’t used native-google stuff, just regular google maps, and declaring var google is necessary.

  3. try declaring your nativeGeocoder as public as opposed to private.

  4. did you run, from the command line, ionic plugin add cordova-plugin-nativegeocoder
    and npm install --save @ionic-native/native-geocoder ?