geolocation.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. $fields.find('.auto-geocode .geofield-lat').val(position.coords.latitude);
  29. $fields.find('.auto-geocode .geofield-lon').val(position.coords.longitude);
  30. }
  31. // don't do anything if we're on field configuration
  32. if (!$(context).find("#edit-instance").length) {
  33. var $fields = $(context);
  34. // check that we have something to fill up
  35. // on muti values check only that the first one is empty
  36. if ($fields.find('.auto-geocode .geofield-lat').val() == '' && $fields.find('.auto-geocode .geofield-lon').val() == '') {
  37. // Check to see if we have geolocation support, either natively or through Google.
  38. if (navigator.geolocation) {
  39. navigator.geolocation.getCurrentPosition(updateLocation);
  40. }
  41. }
  42. }
  43. $(':input[name="geofield-html5-geocode-button"]').once('geofield_geolocation').click(function(e) {
  44. e.preventDefault();
  45. $fields = $(this).parents('.auto-geocode').parent();
  46. if (navigator.geolocation) {
  47. navigator.geolocation.getCurrentPosition(updateLocation);
  48. }
  49. })
  50. }
  51. };
  52. })(jQuery);