7
Extracted from: HTML5 and CSS3, Second Edition Level Up with Today’s Web Technologies This PDF file contains pages extracted from HTML5 and CSS3, Second Edition, published by the Pragmatic Bookshelf. For more information or to purchase a paperback or PDF copy, please visit http://www.pragprog.com. Note: This extract contains some colored text (particularly in code listing). This is available only in online versions of the books. The printed versions are black and white. Pagination might vary between the online and printed versions; the content is otherwise identical. Copyright © 2013 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina

HTML5 and CSS3, Second Editionmedia.pragprog.com/titles/bhh52e/geolocation.pdf · Figure 36—Our current location is marked on the map with a Y. We define the size of the image,

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: HTML5 and CSS3, Second Editionmedia.pragprog.com/titles/bhh52e/geolocation.pdf · Figure 36—Our current location is marked on the map with a Y. We define the size of the image,

Extracted from:

HTML5 and CSS3, Second EditionLevel Up with Today’s Web Technologies

This PDF file contains pages extracted from HTML5 and CSS3, Second Edition,published by the Pragmatic Bookshelf. For more information or to purchase a

paperback or PDF copy, please visit http://www.pragprog.com.

Note: This extract contains some colored text (particularly in code listing). Thisis available only in online versions of the books. The printed versions are blackand white. Pagination might vary between the online and printed versions; the

content is otherwise identical.

Copyright © 2013 The Pragmatic Programmers, LLC.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise,

without the prior consent of the publisher.

The Pragmatic BookshelfDallas, Texas • Raleigh, North Carolina

Page 2: HTML5 and CSS3, Second Editionmedia.pragprog.com/titles/bhh52e/geolocation.pdf · Figure 36—Our current location is marked on the map with a Y. We define the size of the image,
Page 3: HTML5 and CSS3, Second Editionmedia.pragprog.com/titles/bhh52e/geolocation.pdf · Figure 36—Our current location is marked on the map with a Y. We define the size of the image,

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and The PragmaticProgrammers, LLC was aware of a trademark claim, the designations have been printed ininitial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer,Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade-marks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher assumesno responsibility for errors or omissions, or for damages that may result from the use ofinformation (including program listings) contained herein.

Our Pragmatic courses, workshops, and other products can help you and your team createbetter software and have more fun. For more information, as well as the latest Pragmatictitles, please visit us at http://pragprog.com.

The team that produced this book includes:

Susannah Davidson Pfalzer (editor)Potomac Indexing, LLC (indexer)Candace Cunningham (copyeditor)David J Kelly (typesetter)Janet Furlow (producer)Juliet Benda (rights)Ellie Callahan (support)

Copyright © 2013 The Pragmatic Programmers, LLC.All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, ortransmitted, in any form, or by any means, electronic, mechanical, photocopying,recording, or otherwise, without the prior consent of the publisher.

Printed in the United States of America.ISBN-13: 978-1-937785-59-8Encoded using the finest acid-free high-entropy binary digits.Book version: P1.0—October 2013

Page 4: HTML5 and CSS3, Second Editionmedia.pragprog.com/titles/bhh52e/geolocation.pdf · Figure 36—Our current location is marked on the map with a Y. We define the size of the image,

Tip 33

Finding Yourself: Geolocation

Geolocation is a technique for discovering where people are, based on theircomputers’ location. Of course, “computer” really can mean smartphone,tablet, or other portable device as well as a desktop or laptop computer.Geolocation determines a person’s whereabouts by looking at her computer’sIP address, MAC address, Wi-Fi hotspot location, or even GPS coordinates ifavailable. Although it’s not strictly part of the HTML5 specification (and neverwas), Geolocation is often associated with HTML5 because it came on thescene at the same time. Like Web Storage, it’s a very useful technology thatis already implemented in Firefox, Safari, and Chrome. Let’s see how we canuse it.

Locating Awesomeness

We’ve been asked to create a contact page for the AwesomeCo website, andthe CIO has asked whether we can show people’s location on a map alongwith the various AwesomeCo support centers. He’d love to see a prototype,so we’ll get one up and running quickly.

We’ll use Google’s Static Map API for this because it doesn’t require an APIkey and we’re going to generate a very simple map. When we’re done, we’llhave something that looks like Figure 36, Our current location is marked onthe map with a Y, on page 6.

AwesomeCo service centers are located in Portland, Oregon; Chicago, Illinois;and Providence, Rhode Island. Google’s Static Map API makes it really easyto plot these points on a map. All we have to do is construct an img tag andpass the addresses in the URL, like this:

html5_geolocation/index.html<img id="map" alt="Map of AwesomeCo Service Center locations"src="http://maps.google.com/maps/api/staticmap?&amp;size=900x300&amp;sensor=false&amp;maptype=roadmap&amp;markers=color:green|label:A|1+Davol+square,+Providence,+RI+02906-3810&amp;markers=color:green|label:B|22+Southwest+3rd+Avenue,Portland,+OR&amp;markers=color:green|label:C|77+West+Wacker+Drive+Chicago+IL">

• Click HERE to purchase this book now. discuss

Page 5: HTML5 and CSS3, Second Editionmedia.pragprog.com/titles/bhh52e/geolocation.pdf · Figure 36—Our current location is marked on the map with a Y. We define the size of the image,

Figure 36—Our current location is marked on the map with a Y.

We define the size of the image, and then we tell the Maps API that we didnot use any sensor device, such as a client-side geolocation, with the informa-tion we’re passing to this map. Then we define each marker on the map bygiving it a label and an address. We could use comma-separated pairs ofcoordinates for these markers if we had them, but an address is easier forour demonstration.

How to Be Found

We need to plot our visitor’s current location on this map, and we’ll do thatby providing latitude and longitude for a new marker. We can ask thebrowser to grab our visitor’s latitude and longitude, like this:

html5_geolocation/javascripts/geolocation.jsvar getLatitudeAndLongitude = function(){

navigator.geolocation.getCurrentPosition(function(position) {showLocation(position.coords.latitude, position.coords.longitude);

});};

This method prompts the user to provide us with her coordinates. If the visitorallows us to use her location information, we call the showLocation() method.

The showLocation() method takes the latitude and longitude and reconstructsthe image, replacing the existing image source with the new one. Here’s howwe implement that method:

• 6

• Click HERE to purchase this book now. discuss

Page 6: HTML5 and CSS3, Second Editionmedia.pragprog.com/titles/bhh52e/geolocation.pdf · Figure 36—Our current location is marked on the map with a Y. We define the size of the image,

html5_geolocation/javascripts/geolocation.jsvar showLocation = function(lat, lng){Line 1

var fragment = "&markers=color:red|color:red|label:Y|" + lat + "," + lng;2

var image = $("#map");3

var source = image.attr("src") + fragment;4

source = source.replace("sensor=false", "sensor=true");5

image.attr("src", source);6

};7

Rather than duplicate the entire image source code, we’ll append our location’slatitude and longitude to the existing image’s source. Before we assign themodified image source back to the document, we need to change the sensorparameter from false to true. We do that on line 5 with the replace() method.

Finally, we call the getLatitudeAndLongitude() method we defined, which kickseverything off.

html5_geolocation/javascripts/geolocation.jsgetLatitudeAndLongitude();

When we bring up the page in our browser, we see our location, marked witha Y, among the other locations.

Falling Back

As it stands, visitors without Geolocation support will still see the map withthe locations of the AwesomeCo support centers, but they’ll get a JavaScripterror since there’s no Geolocation object available. We need to detect supportfor Geolocation before we attempt to get the visitor’s location. We can useModernizr for that, but where do we get latitude and longitude if we can’t getit from the browser?

Google’s Ajax API does location lookup, so it’s a great fallback solution.9

Our fallback looks like this:

html5_geolocation/javascripts/geolocation.jsvar getLatitudeAndLongitudeWithFallback = function(){Line 1

if ((typeof google === 'object') &&2

google.loader && google.loader.ClientLocation) {3

showLocation(google.loader.ClientLocation.latitude,4

google.loader.ClientLocation.longitude);5

}else{6

var message = $("<p>Couldn't find your address.</p>");7

message.insertAfter("#map");8

}9

};10

9. http://code.google.com/apis/ajax/documentation/#ClientLocation

• Click HERE to purchase this book now. discuss

Finding Yourself: Geolocation • 7

Page 7: HTML5 and CSS3, Second Editionmedia.pragprog.com/titles/bhh52e/geolocation.pdf · Figure 36—Our current location is marked on the map with a Y. We define the size of the image,

We use Google’s ClientLocation() method on line 3 to get a visitor’s location andinvoke our showLocation() method to plot the location on our map.

Then we tell Modernizr to test for Geolocation. If we have support, we’ll callour original method. If we don’t have support, we’ll use a simplified versionof Modernizr.load() to load Google’s library and then call our function to plot thecoordinates.

html5_geolocation/javascripts/geolocation.jsif(Modernizr.geolocation){

getLatitudeAndLongitude();}else{

Modernizr.load({load: "http://www.google.com/jsapi",callback: function(){

getLatitudeAndLongitudeWithFallback();}

});}

Unfortunately, Google can’t geolocate every IP address out there, so we maystill not be able to plot the user on our map; we account for that by placinga message underneath our image on line 7. Our fallback solution isn’t fool-proof, but it does give us a greater chance of locating our visitor.

Without a reliable method of getting coordinates from the client, we need tocome up with a way for the user to provide us with an address, but that’s anexercise I’ll leave up to you.

Next, let’s take a look at HTML5’s built-in support for dragging and droppingelements.

• 8

• Click HERE to purchase this book now. discuss