How to use the Google Maps API on Windows 8

Something that hasn’t been very well documented yet is how to implement the Google Maps API with Windows 8. There are lots of questions about how to do it, but not a lot of answers. Hopefully, this tutorial can help with that.

Before getting into the uber-exciting details, I need to thank Frank LaVigne (@tableteer) for his help. This tutorial would have never been possible without his genius. You can find Frank online at Frank’s World. I’m not a JavaScript expert and Frank was super patient while I asked him tons of questions.

NOTE: If you’re looking for a stupid-easy maps implementation, check out this blog post from G. Andrew Duthie about using Maps app that ships with Windows 8.

Out-of-the-box error

Right now, if you try to include the script for Google Maps API and add a map to the page, you’ll be met with the following error:

clip_image002

Even though you’ve included the source for the script, calling google.maps just doesn’t work. I’ve discovered there are a couple gotchas when implementing the Google Maps API. Keep reading to find out about the secret sauce for Google Maps on Windows 8.

Secret Sauce

Using an iFrame

The first ingredient for the secret sauce is to use an iFrame to display the Google Map. In the tutorial we’ll create a second html page that will have all the information for the Google Map implementation. We’ll create the iFrame in default.html in the tutorial.

Not using page control

The next ingredient in the secret sauce (that technically doesn’t go in) is the page control. For the map html page, we’ll need a map.html, map.js and map.css file. You can get all of these files bundled together by adding a page control. Do NOT do this. The page control also implements some navigation functionality that Google Maps doesn’t know what to do with. This can cause some errors having to do with width offsets that Google Maps doesn’t understand how to implement.

Ms-appx-web

The last, and possibly most important, ingredient for our secret sauce is the use of ms-appx-web in our iFrame src. Due to security restrictions of Windows 8, you can’t load external scripts out-of-the box with the Windows 8 app templates. By using ms-appx-web with our iFrame, we’re able to load locally-packaged content that runs in a web context. For more information, check out How to Reference Content on MSDN.

Tutorial

In this tutorial, we’re going to use the Google Maps API to display earthquake data from the U.S. Geological Survey. The code I’m using to access Google Maps and USGS can be found on the Google Developers Academy site, here. You can download the project here. Please see the end of the post for licensing information.

Set up

Before beginning, you’ll want to make sure your machine is all set up. To develop for Windows 8, you must be running Windows 8. You can download a 90-day evaluation copy here. In addition, you will need Visual Studio 2012 Express for Windows 8 (or higher). The Express version is a free download. You can find it here.

Start developing your Windows 8 app today. Generation App has tons of great resources for developers. Sign up today for tips, great documentation, videos and more!

Create a blank project

The first step for this tutorial is to create a New Project in Visual Studio 2012. This will be a JavaScript project based on the Blank App template. Name your project “MapTutorial.”

clip_image004

Add a map.html/css/js

Now we’ll add the html, css and js file for our map frame that will be referenced from the default.hml page.

Right-click on your project (MapTutorial) in the Solution Explorer and go to Add –> New Item.

clip_image006

Add an HTML Page and call it map.html.

clip_image008

Follow the same process to add map.js and map.css so that your Solution Explorer looks like this:

clip_image010

Add scripts

Now we want to add references to our css and js files in map.html. Open up map.html and the following in the <head> tag:

[sourcecode language="html"]
<!– map references –>
<link href="/map.css" rel="stylesheet" />
<script src="/map.js"></script>
[/sourcecode]

Now we want to add the Google Maps API script. Before the <!– map references –>add the following:

[sourcecode language="html"]
<!– Google Maps API reference –>
<script
src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=visualization">
</script>
[/sourcecode]

So far, so good. There is one more script we’re going to add and that’s the earthquake data we’ll be pulling from the U.S. Geological Survey. After the <!– map references –>add the following:

[sourcecode language="html"]
<!– USGS URL data source –>
<script src = "http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week">
</script>
[/sourcecode]

Your <head> tag should look like this:

[sourcecode language="html"]
<head>
<title></title>

<!– Google Maps API reference –>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=visualization">
</script>

<!– mapframe references –>
<link href="/map.css" rel="stylesheet" />
<script src="/map.js"></script>

<!– USGS URL data source –>
<script src="http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week"></script>

</head>
[/sourcecode]

The last thing we’re going to do with map.html is add a div tag for where we want to display the map. Add the following div tag so the <body> looks like this:

[sourcecode language="html"]
<body>
<div id="mapdisplay"></div>
</body>
[/sourcecode]

At this point if you run your project, you should see a black page and “Content goes here” in the upper left corner.

Add logic

Now that we’ve got our project all set up, let’s add some logic to do something with the earthquake data we’re getting from USGS. I’ve made some changes to the Google Developer code to put things in the right order to work with Windows 8.

In eqfeed_callback , I’ve taken out the logic and put that into addMarkers () which is called from initialize() . In eqfeed_callback (which we need based on the USGS script), I’m saving the results into a global variable to access later. In addition, I’ve commented out setting the icon property for each point. You can uncomment it to see a different way to view the data.

Copy and paste (or write out) the following code in map.js:

[sourcecode language="javascript"]
var map;
var dataResults;

function initialize() {
map = new google.maps.Map(document.getElementById(‘mapdisplay’), {
zoom: 3,
center: new google.maps.LatLng(40, -187.3),
mapTypeId: google.maps.MapTypeId.TERRAIN
});

addMarkers();
}

eqfeed_callback = function (results) {
dataResults = results;
}

function addMarkers () {
for (var i = 0; i < dataResults.features.length; i++) {
var quake = dataResults.features[i];
var coors = quake.geometry.coordinates;
var latLong = new google.maps.LatLng(coors[1], coors[0]);
var marker = new google.maps.Marker({
position: latLong,
map: map
//icon: getCircle(earthquake.properties.mag)
});
}
}

function getCircle(magnitude) {
return {
path: google.maps.SymbolPath.CIRCLE,
fillColor: ‘red’,
fillOpacity: .2,
scale: Math.pow(2, magnitude) / Math.PI,
strokeColor: ‘white’,
strokeWeight: .5
};
}

google.maps.event.addDomListener(window, ‘load’, initialize);
[/sourcecode]

In addition, copy and paste the following code into map.css:

[sourcecode language="css"]
html, body, #mapdisplay {
margin: 0;
padding: 0;
height: 100%;
}
[/sourcecode]

At this point, if you run the project again it should still be a black screen with “Content goes here” in the upper left corner. Don’t worry, we’re going to put content in our app in the next step!

Add an iFrame

Open default.html, if it isn’t already open. In the <body> we’re going to add an iFrame that uses map.html as the source (and a header title). Add the following code so the <body> looks like this:

[sourcecode language="html"]
<body>
<h1>Google Maps API on Windows 8</h1>
<iframe id="Map" src="ms-appx-web:///map.html" style="width:100%;height:100%;"></iframe>
</body>
[/sourcecode]

Run

Now the only thing left for us to do is run the app! You can use F5 or click the green triangle (that looks like a play button) on the Visual Studio tool bar:

clip_image012

At this point you should be seeing your app with a slippy Google Map on it and map markers for where earthquakes have occurred. Yay! You now have the Google Maps API working on Windows 8!! You can download the full project from my SkyDrive.

clip_image014

Portions of this page are reproductions and modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License and Apache 2.0 License. You can find the original pages at Google Developers Academy –> Maps (—> JavaScript) –> Importing Data & Visualizing Data.

16 thoughts on “How to use the Google Maps API on Windows 8

  1. Many thanks, Ed, for this excellent blog. It helped me out a lot with adding Google Maps to my Windows 8 product.

    You are AWESOME! BTW, just playing around with the tutorial, I added the magnitude circles and also titles, showing the place of the quake. What fun!

  2. I using this method to get to google maps in an iframe in my app. Now I’m trying to also reference the Windows.bla namespace in the maps.js and I get an error. var inclinometer = Windows.Devices.Sensors.Inclinometer.getDefault(); throws “JavaScript runtime error: ‘Windows’ is undefined”. Now that I’m in the iFrame, how do i get back to the WinJS namespaces?

  3. With C#/XAML instead of iframe use a WebView and then NavigateToString after reading the HTML content file as a stream. Once the WebView is populated with your googlely goodness you can communicate with it via InvokeScript. So make the reading on the c# side and pass the readings to the JS side.

    To answer my other question above, I can talk to the iframe code using HTML5 iframe.postMessage() on the winJS side and window.addEventListener(“message”,bla…); on the iframe side.

  4. And how is the map webview in Windows 8? I know from Android at least that the webview map is far much slower and limited than the native map component. Of course, here it can’t be compared with Google native map since it doesn’t seem to exists. But probably it can be compared with Bing native map, or native map on other platforms.

  5. I am working on the above post following each and every step carefully but while executing the last step it asked me to enter my network credentials
    I am working with a corporate account and quite possibly it is restricting data from the api
    I entered the required credentials and but to no avail it constantly pops with the same pop-up asking my credentials

    Reply asap

  6. This thing worked
    My only concern now is
    my windows store app(Visual C#>Windows store) requires to plot addresses on the map
    So how do I import this project to work with my store app

  7. How can i pass a value from the page where the iframe is to the map.

    I would like to send a coordinates pair. But I can’t access to the Windows object in there.

    1. Rajan, check the post by Mark near the beginning “With C#/XAML instead of iframe use a WebView…” Just implement a regular HTML page with the Google Maps API then navigate to in your XAML Application using a WebView. It works, but I am still having problems with pinch-zoom, as I mentioned below.

  8. Hello. Thanks for the great post. I was searching for this all over the internet. I was able to get this working on a Metro XAML/C# application (HTML page and navigating to it with a WebView) but somewhow, pinch-zoom does not seem to work…

    Were you able to get the default “pinch to zoom” behavior? Everything else works fine (Drag to pan, double tap to zoom, etc).

    The problem seems to be with the WebView, because the HTML page works fine on a regular browser (even on IE inside the Visual Studio Simulator….)

  9. Hi, i tried the code and it worked in a sample application following every steps you have mentioned.. But.. when i replicated the same code in my Project. It always gives “google” is undefined error. What may be the reason

Leave a Reply