How to show a Google map in your Phonegap app using Google Map api V3, and what whitelist urls to add to your project. This post expect you know how to set up a new Phonegap project.
1. Start by adding a reference to Google maps api in index.html
Then add a div that will contain the map. Choose an id like “map_canvas”. That id will be used to add our map from our javascript later on.
##2. Create a new javascript file called googlemap.js in the www folder and add the following content
and add a reference to it in index.html
the mapOptions variable contains information about zoomlevel, where the center of the map is and what kind of map we want to show. And the line containing the map variable uses getElementById to get our map_canvas and adding the map.
3. Whitelisting google urls
Now we must add the following urls to our Cordova.plist under externalHosts if using Xcode:
*.google.com
*.googleapis.com
*.gstatic.com
4. Showing the map
To show the map we must run the initialize function in googlemap.js. Since we are using the example index.html from phonegap we add these lines to the onDeviceReady function in index.html
Now run the app and you should se a map over Australia.
5. Adding markers
To add markers to our map we use the LatLng and Marker object from Google API. Edit the initialize function in googlemap.js to look like this:
and add the following function, called addMarkersToMap:
Here we added a function called addMarkersToMap and called it from the initialize function. What it’s doing is adding two markers on our map at the given latitude and longitude. And when we create a new marker object, like markerOne, we give the object the position and which map we want to add the marker to.
But if we run the app now we only see one marker. Let’s fix that.
6. Zooming out the map to show all markers
to zoom out the map without knowing which zoomlevel to use we are going to use the LatLngBounds object from the Google Map API.
Start off by adding the following line first in the addMarkersToMap function:
and before the closing tag of the function add these lines:
The addMarkersToMap function now looks like this:
Now we’re done, run the app and the map now zooms out so you can see the marker which we added in Sweden.
I’ve created an example application of this and pushed it to a repository on Github, have a look at it if you want to see the code.