You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 24 KiB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. ---
  2. title: Geolocation
  3. description: Access GPS data.
  4. ---
  5. <!--
  6. # license: Licensed to the Apache Software Foundation (ASF) under one
  7. # or more contributor license agreements. See the NOTICE file
  8. # distributed with this work for additional information
  9. # regarding copyright ownership. The ASF licenses this file
  10. # to you under the Apache License, Version 2.0 (the
  11. # "License"); you may not use this file except in compliance
  12. # with the License. You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing,
  17. # software distributed under the License is distributed on an
  18. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19. # KIND, either express or implied. See the License for the
  20. # specific language governing permissions and limitations
  21. # under the License.
  22. -->
  23. |Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI|
  24. |:-:|:-:|:-:|:-:|:-:|:-:|:-:|
  25. |[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-geolocation.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-geolocation)|
  26. # cordova-plugin-geolocation
  27. This plugin provides information about the device's location, such as
  28. latitude and longitude.
  29. Common sources of location information include
  30. Global Positioning System (GPS) and location inferred from network
  31. signals such as IP address, RFID, WiFi and Bluetooth MAC addresses,
  32. and GSM/CDMA cell IDs. There is no guarantee that the API returns the
  33. device's actual location.
  34. > To get a few ideas, check out the [sample](#sample) at the bottom of this page or go straight to the [reference](#reference) content.
  35. This API is based on the
  36. [W3C Geolocation API Specification](http://dev.w3.org/geo/api/spec-source.html),
  37. and only executes on devices that don't already provide an implementation.
  38. __WARNING__: Collection and use of geolocation data
  39. raises important privacy issues. Your app's privacy policy should
  40. discuss how the app uses geolocation data, whether it is shared with
  41. any other parties, and the level of precision of the data (for
  42. example, coarse, fine, ZIP code level, etc.). Geolocation data is
  43. generally considered sensitive because it can reveal user's
  44. whereabouts and, if stored, the history of their travels.
  45. Therefore, in addition to the app's privacy policy, you should
  46. strongly consider providing a just-in-time notice before the app
  47. accesses geolocation data (if the device operating system doesn't do
  48. so already). That notice should provide the same information noted
  49. above, as well as obtaining the user's permission (e.g., by presenting
  50. choices for __OK__ and __No Thanks__). For more information, please
  51. see the [Privacy Guide](http://cordova.apache.org/docs/en/latest/guide/appdev/privacy/index.html).
  52. This plugin defines a global `navigator.geolocation` object (for platforms
  53. where it is otherwise missing).
  54. Although the object is in the global scope, features provided by this plugin
  55. are not available until after the `deviceready` event.
  56. ```javascript
  57. document.addEventListener("deviceready", onDeviceReady, false);
  58. function onDeviceReady() {
  59. console.log("navigator.geolocation works well");
  60. }
  61. ```
  62. ## <a id="reference"></a>Reference
  63. ## Installation
  64. This requires cordova 5.0+ ( current stable 1.0.0 )
  65. cordova plugin add cordova-plugin-geolocation
  66. Older versions of cordova can still install via the deprecated id ( stale 0.3.12 )
  67. cordova plugin add org.apache.cordova.geolocation
  68. It is also possible to install via repo url directly ( unstable )
  69. cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git
  70. ## Supported Platforms
  71. - Amazon Fire OS
  72. - Android
  73. - BlackBerry 10
  74. - Firefox OS
  75. - iOS
  76. - Tizen
  77. - Windows Phone 7 and 8
  78. - Windows
  79. ## Methods
  80. - navigator.geolocation.getCurrentPosition
  81. - navigator.geolocation.watchPosition
  82. - navigator.geolocation.clearWatch
  83. ## Objects (Read-Only)
  84. - Position
  85. - PositionError
  86. - Coordinates
  87. ## navigator.geolocation.getCurrentPosition
  88. Returns the device's current position to the `geolocationSuccess`
  89. callback with a `Position` object as the parameter. If there is an
  90. error, the `geolocationError` callback is passed a
  91. `PositionError` object.
  92. navigator.geolocation.getCurrentPosition(geolocationSuccess,
  93. [geolocationError],
  94. [geolocationOptions]);
  95. ### Parameters
  96. - __geolocationSuccess__: The callback that is passed the current position.
  97. - __geolocationError__: _(Optional)_ The callback that executes if an error occurs.
  98. - __geolocationOptions__: _(Optional)_ The geolocation options.
  99. ### Example
  100. ```javascript
  101. // onSuccess Callback
  102. // This method accepts a Position object, which contains the
  103. // current GPS coordinates
  104. //
  105. var onSuccess = function(position) {
  106. alert('Latitude: ' + position.coords.latitude + '\n' +
  107. 'Longitude: ' + position.coords.longitude + '\n' +
  108. 'Altitude: ' + position.coords.altitude + '\n' +
  109. 'Accuracy: ' + position.coords.accuracy + '\n' +
  110. 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
  111. 'Heading: ' + position.coords.heading + '\n' +
  112. 'Speed: ' + position.coords.speed + '\n' +
  113. 'Timestamp: ' + position.timestamp + '\n');
  114. };
  115. // onError Callback receives a PositionError object
  116. //
  117. function onError(error) {
  118. alert('code: ' + error.code + '\n' +
  119. 'message: ' + error.message + '\n');
  120. }
  121. navigator.geolocation.getCurrentPosition(onSuccess, onError);
  122. ```
  123. ### iOS Quirks
  124. Since iOS 10 it's mandatory to add a `NSLocationWhenInUseUsageDescription` entry in the info.plist.
  125. `NSLocationWhenInUseUsageDescription` describes the reason that the app accesses the user's location. When the system prompts the user to allow access, this string is displayed as part of the dialog box. To add this entry you can pass the variable `GEOLOCATION_USAGE_DESCRIPTION` on plugin install.
  126. Example:
  127. `cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="your usage message"`
  128. If you don't pass the variable, the plugin will add an empty string as value.
  129. ### Android Quirks
  130. If Geolocation service is turned off the `onError` callback is invoked after `timeout` interval (if specified).
  131. If `timeout` parameter is not specified then no callback is called.
  132. ## navigator.geolocation.watchPosition
  133. Returns the device's current position when a change in position is detected.
  134. When the device retrieves a new location, the `geolocationSuccess`
  135. callback executes with a `Position` object as the parameter. If
  136. there is an error, the `geolocationError` callback executes with a
  137. `PositionError` object as the parameter.
  138. var watchId = navigator.geolocation.watchPosition(geolocationSuccess,
  139. [geolocationError],
  140. [geolocationOptions]);
  141. ### Parameters
  142. - __geolocationSuccess__: The callback that is passed the current position.
  143. - __geolocationError__: (Optional) The callback that executes if an error occurs.
  144. - __geolocationOptions__: (Optional) The geolocation options.
  145. ### Returns
  146. - __String__: returns a watch id that references the watch position interval. The watch id should be used with `navigator.geolocation.clearWatch` to stop watching for changes in position.
  147. ### Example
  148. ```javascript
  149. // onSuccess Callback
  150. // This method accepts a `Position` object, which contains
  151. // the current GPS coordinates
  152. //
  153. function onSuccess(position) {
  154. var element = document.getElementById('geolocation');
  155. element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
  156. 'Longitude: ' + position.coords.longitude + '<br />' +
  157. '<hr />' + element.innerHTML;
  158. }
  159. // onError Callback receives a PositionError object
  160. //
  161. function onError(error) {
  162. alert('code: ' + error.code + '\n' +
  163. 'message: ' + error.message + '\n');
  164. }
  165. // Options: throw an error if no update is received every 30 seconds.
  166. //
  167. var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });
  168. ```
  169. ## geolocationOptions
  170. Optional parameters to customize the retrieval of the geolocation
  171. `Position`.
  172. { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };
  173. ### Options
  174. - __enableHighAccuracy__: Provides a hint that the application needs the best possible results. By default, the device attempts to retrieve a `Position` using network-based methods. Setting this property to `true` tells the framework to use more accurate methods, such as satellite positioning. _(Boolean)_
  175. - __timeout__: The maximum length of time (milliseconds) that is allowed to pass from the call to `navigator.geolocation.getCurrentPosition` or `geolocation.watchPosition` until the corresponding `geolocationSuccess` callback executes. If the `geolocationSuccess` callback is not invoked within this time, the `geolocationError` callback is passed a `PositionError.TIMEOUT` error code. (Note that when used in conjunction with `geolocation.watchPosition`, the `geolocationError` callback could be called on an interval every `timeout` milliseconds!) _(Number)_
  176. - __maximumAge__: Accept a cached position whose age is no greater than the specified time in milliseconds. _(Number)_
  177. ### Android Quirks
  178. If Geolocation service is turned off the `onError` callback is invoked after `timeout` interval (if specified).
  179. If `timeout` parameter is not specified then no callback is called.
  180. ## navigator.geolocation.clearWatch
  181. Stop watching for changes to the device's location referenced by the
  182. `watchID` parameter.
  183. navigator.geolocation.clearWatch(watchID);
  184. ### Parameters
  185. - __watchID__: The id of the `watchPosition` interval to clear. (String)
  186. ### Example
  187. ```javascript
  188. // Options: watch for changes in position, and use the most
  189. // accurate position acquisition method available.
  190. //
  191. var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });
  192. // ...later on...
  193. navigator.geolocation.clearWatch(watchID);
  194. ```
  195. ## Position
  196. Contains `Position` coordinates and timestamp, created by the geolocation API.
  197. ### Properties
  198. - __coords__: A set of geographic coordinates. _(Coordinates)_
  199. - __timestamp__: Creation timestamp for `coords`. _(DOMTimeStamp)_
  200. ## Coordinates
  201. A `Coordinates` object is attached to a `Position` object that is
  202. available to callback functions in requests for the current position.
  203. It contains a set of properties that describe the geographic coordinates of a position.
  204. ### Properties
  205. * __latitude__: Latitude in decimal degrees. _(Number)_
  206. * __longitude__: Longitude in decimal degrees. _(Number)_
  207. * __altitude__: Height of the position in meters above the ellipsoid. _(Number)_
  208. * __accuracy__: Accuracy level of the latitude and longitude coordinates in meters. _(Number)_
  209. * __altitudeAccuracy__: Accuracy level of the altitude coordinate in meters. _(Number)_
  210. * __heading__: Direction of travel, specified in degrees counting clockwise relative to the true north. _(Number)_
  211. * __speed__: Current ground speed of the device, specified in meters per second. _(Number)_
  212. ### Amazon Fire OS Quirks
  213. __altitudeAccuracy__: Not supported by Android devices, returning `null`.
  214. ### Android Quirks
  215. __altitudeAccuracy__: Not supported by Android devices, returning `null`.
  216. ## PositionError
  217. The `PositionError` object is passed to the `geolocationError`
  218. callback function when an error occurs with navigator.geolocation.
  219. ### Properties
  220. - __code__: One of the predefined error codes listed below.
  221. - __message__: Error message describing the details of the error encountered.
  222. ### Constants
  223. - `PositionError.PERMISSION_DENIED`
  224. - Returned when users do not allow the app to retrieve position information. This is dependent on the platform.
  225. - `PositionError.POSITION_UNAVAILABLE`
  226. - Returned when the device is unable to retrieve a position. In general, this means the device is not connected to a network or can't get a satellite fix.
  227. - `PositionError.TIMEOUT`
  228. - Returned when the device is unable to retrieve a position within the time specified by the `timeout` included in `geolocationOptions`. When used with `navigator.geolocation.watchPosition`, this error could be repeatedly passed to the `geolocationError` callback every `timeout` milliseconds.
  229. ## <a id="sample"></a>Sample: Get the weather, find stores, and see photos of things nearby with Geolocation ##
  230. Use this plugin to help users find things near them such as Groupon deals, houses for sale, movies playing, sports and entertainment events and more.
  231. Here's a "cookbook" of ideas to get you started. In the snippets below, we'll show you some basic ways to add these features to your app.
  232. * [Get your coordinates](#coords).
  233. * [Get the weather forecast](#weather).
  234. * [Receive updated weather forecasts as you drive around](#receive).
  235. * [See where you are on a map](#see).
  236. * [Find stores near you](#find).
  237. * [See pictures of things around you](#see).
  238. ## <a id="coord"></a>Get your geolocation coordinates
  239. ```javascript
  240. function getWeatherLocation() {
  241. navigator.geolocation.getCurrentPosition
  242. (onWeatherSuccess, onWeatherError, { enableHighAccuracy: true });
  243. }
  244. ```
  245. ## <a id="weather"></a>Get the weather forecast
  246. ```javascript
  247. // Success callback for get geo coordinates
  248. var onWeatherSuccess = function (position) {
  249. Latitude = position.coords.latitude;
  250. Longitude = position.coords.longitude;
  251. getWeather(Latitude, Longitude);
  252. }
  253. // Get weather by using coordinates
  254. function getWeather(latitude, longitude) {
  255. // Get a free key at http://openweathermap.org/. Replace the "Your_Key_Here" string with that key.
  256. var OpenWeatherAppKey = "Your_Key_Here";
  257. var queryString =
  258. 'http://api.openweathermap.org/data/2.5/weather?lat='
  259. + latitude + '&lon=' + longitude + '&appid=' + OpenWeatherAppKey + '&units=imperial';
  260. $.getJSON(queryString, function (results) {
  261. if (results.weather.length) {
  262. $.getJSON(queryString, function (results) {
  263. if (results.weather.length) {
  264. $('#description').text(results.name);
  265. $('#temp').text(results.main.temp);
  266. $('#wind').text(results.wind.speed);
  267. $('#humidity').text(results.main.humidity);
  268. $('#visibility').text(results.weather[0].main);
  269. var sunriseDate = new Date(results.sys.sunrise);
  270. $('#sunrise').text(sunriseDate.toLocaleTimeString());
  271. var sunsetDate = new Date(results.sys.sunrise);
  272. $('#sunset').text(sunsetDate.toLocaleTimeString());
  273. }
  274. });
  275. }
  276. }).fail(function () {
  277. console.log("error getting location");
  278. });
  279. }
  280. // Error callback
  281. function onWeatherError(error) {
  282. console.log('code: ' + error.code + '\n' +
  283. 'message: ' + error.message + '\n');
  284. }
  285. ```
  286. ## <a id="receive"></a>Receive updated weather forecasts as you drive around
  287. ```javascript
  288. // Watch your changing position
  289. function watchWeatherPosition() {
  290. return navigator.geolocation.watchPosition
  291. (onWeatherWatchSuccess, onWeatherError, { enableHighAccuracy: true });
  292. }
  293. // Success callback for watching your changing position
  294. var onWeatherWatchSuccess = function (position) {
  295. var updatedLatitude = position.coords.latitude;
  296. var updatedLongitude = position.coords.longitude;
  297. if (updatedLatitude != Latitude && updatedLongitude != Longitude) {
  298. Latitude = updatedLatitude;
  299. Longitude = updatedLongitude;
  300. // Calls function we defined earlier.
  301. getWeather(updatedLatitude, updatedLongitude);
  302. }
  303. }
  304. ```
  305. ## <a id="see"></a>See where you are on a map
  306. Both Bing and Google have map services. We'll use Google's. You'll need a key but it's free if you're just trying things out.
  307. Add a reference to the **maps** service.
  308. ```HTML
  309. <script src="https://maps.googleapis.com/maps/api/js?key=Your_API_Key"></script>
  310. ```
  311. Then, add code to use it.
  312. ```javascript
  313. var Latitude = undefined;
  314. var Longitude = undefined;
  315. // Get geo coordinates
  316. function getMapLocation() {
  317. navigator.geolocation.getCurrentPosition
  318. (onMapSuccess, onMapError, { enableHighAccuracy: true });
  319. }
  320. // Success callback for get geo coordinates
  321. var onMapSuccess = function (position) {
  322. Latitude = position.coords.latitude;
  323. Longitude = position.coords.longitude;
  324. getMap(Latitude, Longitude);
  325. }
  326. // Get map by using coordinates
  327. function getMap(latitude, longitude) {
  328. var mapOptions = {
  329. center: new google.maps.LatLng(0, 0),
  330. zoom: 1,
  331. mapTypeId: google.maps.MapTypeId.ROADMAP
  332. };
  333. map = new google.maps.Map
  334. (document.getElementById("map"), mapOptions);
  335. var latLong = new google.maps.LatLng(latitude, longitude);
  336. var marker = new google.maps.Marker({
  337. position: latLong
  338. });
  339. marker.setMap(map);
  340. map.setZoom(15);
  341. map.setCenter(marker.getPosition());
  342. }
  343. // Success callback for watching your changing position
  344. var onMapWatchSuccess = function (position) {
  345. var updatedLatitude = position.coords.latitude;
  346. var updatedLongitude = position.coords.longitude;
  347. if (updatedLatitude != Latitude && updatedLongitude != Longitude) {
  348. Latitude = updatedLatitude;
  349. Longitude = updatedLongitude;
  350. getMap(updatedLatitude, updatedLongitude);
  351. }
  352. }
  353. // Error callback
  354. function onMapError(error) {
  355. console.log('code: ' + error.code + '\n' +
  356. 'message: ' + error.message + '\n');
  357. }
  358. // Watch your changing position
  359. function watchMapPosition() {
  360. return navigator.geolocation.watchPosition
  361. (onMapWatchSuccess, onMapError, { enableHighAccuracy: true });
  362. }
  363. ```
  364. ## <a id="find"></a>Find stores near you
  365. You can use the same Google key for this.
  366. Add a reference to the **places** service.
  367. ```HTML
  368. <script src=
  369. "https://maps.googleapis.com/maps/api/js?key=Your_API_Key&libraries=places">
  370. </script>
  371. ```
  372. Then, add code to use it.
  373. ```javascript
  374. var Map;
  375. var Infowindow;
  376. var Latitude = undefined;
  377. var Longitude = undefined;
  378. // Get geo coordinates
  379. function getPlacesLocation() {
  380. navigator.geolocation.getCurrentPosition
  381. (onPlacesSuccess, onPlacesError, { enableHighAccuracy: true });
  382. }
  383. // Success callback for get geo coordinates
  384. var onPlacesSuccess = function (position) {
  385. Latitude = position.coords.latitude;
  386. Longitude = position.coords.longitude;
  387. getPlaces(Latitude, Longitude);
  388. }
  389. // Get places by using coordinates
  390. function getPlaces(latitude, longitude) {
  391. var latLong = new google.maps.LatLng(latitude, longitude);
  392. var mapOptions = {
  393. center: new google.maps.LatLng(latitude, longitude),
  394. zoom: 15,
  395. mapTypeId: google.maps.MapTypeId.ROADMAP
  396. };
  397. Map = new google.maps.Map(document.getElementById("places"), mapOptions);
  398. Infowindow = new google.maps.InfoWindow();
  399. var service = new google.maps.places.PlacesService(Map);
  400. service.nearbySearch({
  401. location: latLong,
  402. radius: 500,
  403. type: ['store']
  404. }, foundStoresCallback);
  405. }
  406. // Success callback for watching your changing position
  407. var onPlacesWatchSuccess = function (position) {
  408. var updatedLatitude = position.coords.latitude;
  409. var updatedLongitude = position.coords.longitude;
  410. if (updatedLatitude != Latitude && updatedLongitude != Longitude) {
  411. Latitude = updatedLatitude;
  412. Longitude = updatedLongitude;
  413. getPlaces(updatedLatitude, updatedLongitude);
  414. }
  415. }
  416. // Success callback for locating stores in the area
  417. function foundStoresCallback(results, status) {
  418. if (status === google.maps.places.PlacesServiceStatus.OK) {
  419. for (var i = 0; i < results.length; i++) {
  420. createMarker(results[i]);
  421. }
  422. }
  423. }
  424. // Place a pin for each store on the map
  425. function createMarker(place) {
  426. var placeLoc = place.geometry.location;
  427. var marker = new google.maps.Marker({
  428. map: Map,
  429. position: place.geometry.location
  430. });
  431. google.maps.event.addListener(marker, 'click', function () {
  432. Infowindow.setContent(place.name);
  433. Infowindow.open(Map, this);
  434. });
  435. }
  436. // Error callback
  437. function onPlacesError(error) {
  438. console.log('code: ' + error.code + '\n' +
  439. 'message: ' + error.message + '\n');
  440. }
  441. // Watch your changing position
  442. function watchPlacesPosition() {
  443. return navigator.geolocation.watchPosition
  444. (onPlacesWatchSuccess, onPlacesError, { enableHighAccuracy: true });
  445. }
  446. ```
  447. ## <a id="pictures"></a>See pictures of things around you
  448. Digital photos can contain geo coordinates that identify where the picture was taken.
  449. Use Flickr API's to find pictures that folks have taken near you. Like Google services, you'll need a key, but it's free if you just want to try things out.
  450. ```javascript
  451. var Latitude = undefined;
  452. var Longitude = undefined;
  453. // Get geo coordinates
  454. function getPicturesLocation() {
  455. navigator.geolocation.getCurrentPosition
  456. (onPicturesSuccess, onPicturesError, { enableHighAccuracy: true });
  457. }
  458. // Success callback for get geo coordinates
  459. var onPicturesSuccess = function (position) {
  460. Latitude = position.coords.latitude;
  461. Longitude = position.coords.longitude;
  462. getPictures(Latitude, Longitude);
  463. }
  464. // Get pictures by using coordinates
  465. function getPictures(latitude, longitude) {
  466. $('#pictures').empty();
  467. var queryString =
  468. "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=Your_API_Key&lat="
  469. + latitude + "&lon=" + longitude + "&format=json&jsoncallback=?";
  470. $.getJSON(queryString, function (results) {
  471. $.each(results.photos.photo, function (index, item) {
  472. var photoURL = "http://farm" + item.farm + ".static.flickr.com/" +
  473. item.server + "/" + item.id + "_" + item.secret + "_m.jpg";
  474. $('#pictures').append($("<img />").attr("src", photoURL));
  475. });
  476. }
  477. );
  478. }
  479. // Success callback for watching your changing position
  480. var onPicturesWatchSuccess = function (position) {
  481. var updatedLatitude = position.coords.latitude;
  482. var updatedLongitude = position.coords.longitude;
  483. if (updatedLatitude != Latitude && updatedLongitude != Longitude) {
  484. Latitude = updatedLatitude;
  485. Longitude = updatedLongitude;
  486. getPictures(updatedLatitude, updatedLongitude);
  487. }
  488. }
  489. // Error callback
  490. function onPicturesError(error) {
  491. console.log('code: ' + error.code + '\n' +
  492. 'message: ' + error.message + '\n');
  493. }
  494. // Watch your changing position
  495. function watchPicturePosition() {
  496. return navigator.geolocation.watchPosition
  497. (onPicturesWatchSuccess, onPicturesError, { enableHighAccuracy: true });
  498. }
  499. ```