*Note: This is an older post that I haven’t kept updated with formatting for code samples. So, sorry. I think you’ll be able to figure it out though. I believe in you!*
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:
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.”
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.
Add an HTML Page and call it map.html.
Follow the same process to add map.js and map.css so that your Solution Explorer looks like this:
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:
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.
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.
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!
I’m so glad it helped you! I’d love to hear about your project 🙂
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?
How to use it with C#/XAML? I have already an application written in C#/XAML and want to add Google Maps API.
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.
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.
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
Error resolved 🙂
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
Reply awaited
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.
Good respond in return of this issue with firm arguments and explaining everything on
the topic of that.
Can you please post an article on using Google Maps in Windows 8 metro app using C# and XAML?
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.
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….)
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
i’m getting a error at line
” map = new google.maps.Map(document.getElementById(‘mapdisplay’)” in map.js showing “mapdisplay” is a invalid character
tq very much , very nice article
it doesn’t function. i try it in visual studio 2013 and click simulate but the map isn’t shown. don’t give the error “google is undefined” but there is no map on the page. i try also to put the key=mykey (with my real key) but doesn’t work. any suggestion?
I better explain. I load your project directly on visual studio 2013 and it works. what I’m trying to do is import the file css, js, and html in my windows phonegap project but it doesn’t work in sense that the map is not charged. I had imported the default files and in the index.html I put a link on default.html.
it gives me an error:
APPHOST9623: The app couldn’t resolve ms-appx-web://io.cordova.hellocordova/map.html because of this error: RESOURCE_NOT_FOUND.
except that default.js and index.js both start the app and this could create conflict.
have you suggestion why your project if run show the map and my not. ty
Francisco, do you solved this?
Will this work if you are using google maps api for work? There you get an ApiKey from google, and you are required to provide the apiKey with the request to load the js, and you have to register the referer URL (the url to which you embed the google maps, e.g. http://www.creepyed.com, if you want to embed googlemap to this blog site), but they do not allow you to register a URL like ms-appx-web://blablabla.
I used this. It’s worked only Your Project. I copied all files in my Project it’s not working always show “google is undefined” error.I think it’s problem in WinJS because I use 2.0 winJs in my Project and in your project it’s 1.0 . Give me any solution for that. Thanks.
After spending 1.5 day, your post solved the problem. The ms-appx-web:/// was my blind spot.
plz give the full controls of google map API`s in windows phone application through html so that I will make my application thanks