Tuesday, 16 April 2013

PhoneGap + Android + Google Maps Api V3 + OpenStreetMaps

Hi Guys,

Well, I have been kind of researching on creating android applications using HTML5 for a few days. I thought, better start with a demo of maps on android. Since Google poses very strict usage policies regarding its maps, I opted to go with OpenStreetMaps to avoid all the plagiarism, copyright and whatever issues.  

Anyways, enough of other talks. Here is what I am going to show you guys.

I am going to develop an PhoneGap application, demonstrating the use OpenStreetMaps with Google maps api V3 for Android devices. 



Pre-requirements:
1. Eclipse with android SDK (Offcourse).
2. Latest version of PhoneGap from here.
3. A few basic on documentation of OpenStreetMap tiles as a layer within a Google Map from this link here.

Set-up 
Well assuming that you have downloaded PhoneGap, kindly import the example for android into your eclipse. Your example for android should be placed in a path which looks something like this:

phonegap-2.3.0\lib\android\example

Well, once having imported, never bother about the source folder. Go straight away to "assets" folder and open index.html file. 

For all those people new to PhoneGap, here is small helpful tip from what I have understood. PhoneGap helps provide a touch interface to web layer. In layman words, PhoneGap helps convert mouse clicks on normal desktops to touch interface on mobile devices.

Let's start coding
Well, before starting the coding, kindly have a look at documentation of using OpenStreetMap tiles as a layer within a Google Map, in the link provided here. Copy the "Example Using Google Maps API V3 o" code in a notepad, name the file as some Test.html and double click it. The file should open in your default browser showing OpenStreetMaps.

Now, all I will be doing is use the same code in index.html with a few small alterations.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Google Maps v3 API Example</title>
         
         // Create CSS layer for displaying maps on mobile devices
         <style type="text/css">
            html, body, #map {
                height: 100%;
                margin: 0;
                padding: 0;
            }
        </style>
        
        //Identify the device whether android or ios
        <script>
            if (navigator.userAgent.toLowerCase().match(/android/)) {
                document.write('<script charset="utf-8" src="cordova-1.5.0-android.js"><\/script>');
            } else if (navigator.userAgent.toLowerCase().match(/iphone/) || navigator.userAgent.toLowerCase().match(/ipad/)) {
                document.write('<script charset="utf-8" src="cordova-1.5.0.js"><\/script>');
            }
        </script>
    
    </head>
    <body>
        <div id="map"></div>
 
         <!-- bring in the google maps library -->
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
 
        <script type="text/javascript">
          
            //Google maps API initialisation
            var element = document.getElementById("map");
 
            //Define the properties of the OSM map to be displayed
            var map = new google.maps.Map(element, {
                center: new google.maps.LatLng(57, 21),
                zoom: 3,
                mapTypeId: "OSM",
                mapTypeControl: false,
                streetViewControl: false
            });
 
            //Define OSM map type pointing at the OpenStreetMap tile server
            map.mapTypes.set("OSM", new google.maps.ImageMapType({
                getTileUrl: function(coord, zoom) {
                    return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
                },
                tileSize: new google.maps.Size(256, 256),
                name: "OpenStreetMap",
                maxZoom: 18
            }));
        </script>
    </body>
</html>

Hope the code is self explanatory with all those comments. So, I mention it again, all you need to do is place the above code in index.html file in your assets folder and the application is ready to work. You need not starch your head on altering permissions in Android Manifest for PhoneGap helps take care of all those requirements. 

Kindly feel free to leave your comments if you found this article helpful. Also, leave me any queries in the comments section, and I would try getting back to you ASAP.

Thanks guys.

10 comments:

  1. hi if we need to keep any markers here means how to do it?

    ReplyDelete
  2. Call the below function from you onLoad method (Method that is called when initializing the maps):

    var addMarkersToMap = function(map) {

    var mapBounds = new google.maps.LatLngBounds();
    mapBounds.extend(sourceMarker);
    map.fitBounds(mapBounds);

    markerPosition = new google.maps.Marker({
    position: sourceMarker,
    map: map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    icon: "http://**********/c3icons/" + userName + ".png", //Give URL for Icon
    weight: 10,
    title: 'Current Location',
    });

    Where,

    sourceMarker = new google.maps.LatLng(latitude, longitude); (Sub values for latitude and longitude)

    Hopefully this helps you.

    Thanks.

    ReplyDelete
  3. Thanks a lot for a wonderful blog. I started implement google map with phonegap and got lot of issues and was not able to solution it for 3 days. Your blog helped me to do it in 10 mins. Thanks again.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Thanks Siva.. Its my pleasure that I could be of some help to you :)

      Delete
  4. Nice Blog. whether we should add sourceMarker = new google.maps.LatLng(latitude, longitude); this line in our code,where should we add.

    ReplyDelete
  5. Very nice!! Busy with a school project and this helps. Was wondering what would I need to do so it shows my current location??

    ReplyDelete
  6. i am having an error as,
    "google is not defined at file"
    can you please suggest a solution ?

    ReplyDelete
  7. Ooops mate the map is not loading .. I can only see a white screen on my Nexus 4 ..

    ReplyDelete