geocoder.geocode callback is never called in ionic cordova

1.3k views Asked by At

I have a ionic/cordova android project where I try to fetch the location for some coordinates inside a service; maps sdk is loaded alright and in my service, I have the following:

var lat = 30;  // example
var lng = 32;  // example
var geocoder = new google.maps.Geocoder();  // geocoder is not undefined here
var latlng = new google.maps.LatLng(lat, lng);

geocoder.geocode({'location': latlng}, function(results, status) {
    console.log("geocoder.geocode callback"); // never printed ...
});

In the HTML, the API is loaded like this:

<script type="text/javascript"
    src="https://maps.googleapis.com/maps/api/js?v=3&key=MOBILE_API_KEY"></script>

Any idea what am I doing wrong here?

[EDIT]

I tried removing the key argument from the script loading url; no changes there; accessing the app through the browser, geocoder.geocode worked alright; running it with the android emulator or in an android device, it did not work. Could this be permission related or something?

By the way, my content-security-policy is set as follow, for now:

[EDIT2]

Just made an pen with a ionic project example; create a project with:

ionic start TheBlank blank

and copy the code. http://codepen.io/anon/pen/RPxNaL

// add the android platform 
ionic platform add android 
// run the project on device
ionic run android // geocode callback will not work here
ionic serve // geocode callback will work here
1

There are 1 answers

0
Italo Maia On

The problem was somehow related to ionic. After using cordova to run and emulate, things started working. I tested this with the ionic-starter-maps template. To do it yourself, try this:

ionic start MyMaps maps
ionic platform add android
ionic emulate android  # won't work

ionic start MyMaps maps
cordova platform add android
cordova emulate android  # works!

Also, make sure content-security-policy has the required rules:

<meta http-equiv="Content-Security-Policy" content="
        default-src 'self' data: gap:
            https://ssl.gstatic.com;
        script-src 'self' 'unsafe-inline' 'unsafe-eval'
            https://maps.gstatic.com https://maps.googleapis.com;
        img-src     'self'
            https://maps.gstatic.com https://maps.googleapis.com;
        style-src   'self' 'unsafe-inline' *;
        media-src   *;">