geolocation.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // geo-location shim
  2. // Source: https://gist.github.com/366184
  3. // currentely only serves lat/long
  4. // depends on jQuery
  5. ;(function(geolocation, $){
  6. if (geolocation) return;
  7. var cache;
  8. geolocation = window.navigator.geolocation = {};
  9. geolocation.getCurrentPosition = function(callback){
  10. if (cache) callback(cache);
  11. $.getScript('//www.google.com/jsapi',function(){
  12. cache = {
  13. coords : {
  14. "latitude": google.loader.ClientLocation.latitude,
  15. "longitude": google.loader.ClientLocation.longitude
  16. }
  17. };
  18. callback(cache);
  19. });
  20. };
  21. geolocation.watchPosition = geolocation.getCurrentPosition;
  22. })(navigator.geolocation, jQuery);
  23. ;(function ($) {
  24. Drupal.behaviors.geofieldGeolocation = {
  25. attach: function (context, settings) {
  26. // callback for getCurrentPosition
  27. function updateLocation(position) {
  28. // @TODO: calculate bounding box from accuracy value (accuracy is in meters)
  29. $fields.find('.geofield_lat').val(position.coords.latitude);
  30. $fields.find('.geofield_lon').val(position.coords.longitude);
  31. }
  32. // don't do anything if we're on field configuration
  33. if (!$(context).find("#edit-instance").length) {
  34. var $fields = $(context).find('.field-widget-geofield-geolocation');
  35. // check that we have something to fill up
  36. // on muti values check only that the first one is empty
  37. if ($fields.find('.geofield_lat').val() == '' && $fields.find('.geofield_lon').val() == '') {
  38. // very simple geolocation, no fallback support
  39. if (navigator.geolocation) {
  40. navigator.geolocation.getCurrentPosition(updateLocation);
  41. }
  42. }
  43. }
  44. }
  45. };
  46. })(jQuery);