Implement Google Maps API on PhoneGap Using the Device API

Implement Google Maps API on PhoneGap Using the Device API

Introduction

In previous articles, I have touched on installing PhoneGap on Windows and Mac OS X, as well as getting jQuery Mobile and PhoneGap working together. In this article we are going to look at how to use Google Maps API together with PhoneGap to create a map that is interactive. Google Maps is a mapping service provided by Google, and allows you to add interesting functionality to your application without too much blood, sweat or tears.

Installing PhoneGap and Geolocation APIs

I’m going to assume you have followed these instructions, or you already have a working version of PhoneGap on your machine. Once you are ready, fire up your command-line interface—Terminal on OS X or CMD on Windows—and navigate to your PhoneGap application, as I have done below. My project is located in my Home/Server/phonegap, and a directory listing shows my PhoneGap application has four directories—merges, platforms, plugins and www. See figure 1:


Figure 1

In the Root directory of the application, as you can see in Figure 1, I am going to tell PhoneGap to install the Accelerometer, Compass and Geolocation PhoneGap plugins using the command line. The commands are:

$ phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device-motion.git$ phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation.git$ phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git

And Figure 2 shows my Terminal console after running these commands.


Figure 2

To confirm that these plugins are installed, we can simply look at our project and see the files. In my IDE, the directory structure is shown in Figure 3. Notice the plugin directory—our Device Motion, Device Orientation and Geolocation APIs are installed there. The Device Motion API detects the device speed, the Device Orientation detects the device Direction, and the Geolocation API plugs into the device GPS and allows us to pass our location to Google Maps API.


Figure 3

Install Google Maps API

The Google Maps API requires you to create an API key to use with your application. This is a security measure, making sure that only your application has access to your API. Head over to https://code.google.com/apis/console and login with your Google account. Once there, you’ll see a menu option in the left sidebar called APIs & Auth. Click on that, and a submenu will open the APIs button. Make sure that Google Maps API v3 is active, as seen in Figure 4.


Figure 4

Next, click on the Credentials option in the sidebar and then on the red block that says Create New Key. You will see a new popup as shown in Figure 5.


Figure 5

Choose “Browser Key” and continue. The next screen in the popup is shown in Figure 6.


Figure 6

To add an HTTP Referrer, you can add * for now, as you application is not being deployed to a specific URL. This wildcard should be updated later, though, when you go live. Click create, and you will see your new key—see Figure 7.


Figure 7

Remember that API key. Keep it somewhere (of course you can always come back to this page and find it.)


Figure 8

Figure 8 shows our project/www/index.html file. This is the default file structure for a PhoneGap project. When we run this page, we see the screen as shown in Figure 9. This page is just used to show you that PhoneGap has managed to access your device, and is ready to work.


Figure 9

The first thing we need to do is insert the Google Maps API into the index.html page, and the format for this is:

Figure 10 shows my index.html page with the Google maps API key inserted into the JavaScript tag in the footer. This tag gets authentication from Google’s servers and then sits back and waits for you to tell it what to do, and that is the thing we are going to get to next. Let’s look at the contents of the file www/js/index.js. If you have followed the first two articles in this series, linked in the introduction, you will know what this file is. If you are not sure, please go check that out now, and then head on back so we can continue.


Figure 10


Figure 11

Figure 11 shows my www/js/index.js file, and this is the default PhoneGap stuff in here, automatically generated when you create your project. But this doesn’t actually do anything, so I’m going to remove the method called receivedEvent and I’m going to remove the contents of the method onDeviceReady. This is where we are going to put our Google maps code. So, before we continue, look at Figure 12 and make sure you have a similar setup.


Figure 12

Getting Our Location

The first thing we need to do is determine our location. We can do this thanks to your device (which hopefully has a GPS installed) and the Geolocation Plugin you installed in PhoneGap at the start of this article.

To get our location, we have to call a PhoneGap method called getCurrentPosition. To do this we call:

navigator.geolocation.getCurrentPosition(onSuccess, onError); 

The arguments onSuccess and onError are names of callback methods we are going to use depending on whether our device finds our location or not. We can use the onSuccess callback to contain the code for showing our map. The onError callback can be used to alert the error. Of course, we can call those callbacks anything we want to.

The first thing we need to do is update the index.html page to simply contain a div that will contain our Google Map. See Figure 13 for how I did this. Note that I just styled the div for an iPhone 5’s resolution.


Figure 13

Once I update the code to include the onError and onSuccess callbacks, which will call the Google map, our code in index.js is:


Figure 14

Breaking down Figure 14, we see the following:

  • Line 37—we call the getCurrentPosition method, which locks into our device GPS and figures out where we are.
  • Line 42—The onSuccess method, and the position object is passed into it.
  • Line 44—Define our longitude
  • Line 45—Define our latitude
  • Line 46—latLong is defined as an object by our Google maps API and our location.
  • Line 49—The mapOptions object is constructed, and this is passed into the map object (line 55)
  • Line 50—We tell the map to center on our location
  • Line 51—We tell Google Maps what our zoom level is.
  • Line 52—We tell Google Maps which map type to use. Options are ROADMAP, SATELLITE, HYBRID and TERRAIN.
  • Line 55—We call the Google Maps API method which will deliver the map, and tell it which div to load the map into (“#geolocation”).

When we fire up our emulator, we see the app load and then ask for permission to use our location, as in Figure 15.


Figure 15

Once we give permission to use our location, we watch as the Google Map loads, with our location centered as requested.


Figure 16

Conclusion

We have reached the limit of the scope of this article. For further reading regarding this topic, please see https://developers.google.com/maps/documentation/javascript/tutorial and http://docs.phonegap.com/en/edge/cordova_geolocation_geolocation.md.html – Geolocation.

devx-admin

devx-admin

Share the Post:
5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time