GeoLocation脚本用于刷新用户的位置

时间:2012-02-25 06:16:54

标签: geolocation

我有以下GeoLocation脚本来查找用户的位置。如果点击按钮刷新用户的位置以防他们移动位置,我将如何进行合并?换句话说,我正在寻找一个html按钮,可以在点击时刷新用户的位置。

            // Find user's location start
            jQuery(window).ready(function () {
                 geo_latitude = jQuery.cookie('geo_latitude');
                 geo_longitude = jQuery.cookie('geo_longitude');
                 jQuery.cookie('the_cookie', 'the_value', { expires: 7 });

                 if(null!=geo_latitude && null!=geo_longitude){
                     var position = {
                         coords : { latitude : geo_latitude, longitude : geo_longitude }
                     };
                     handle_geolocation_query(position);
                 }else{
                     initiate_geolocation();
                 }


             })
             function initiate_geolocation() {
                 console.log('initiate_geolocation');
                 if(navigator.geolocation) {
                     navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
                 } else {
                     yqlgeo.get('visitor', normalize_yql_response);
                 }

             }

             function handle_errors(error) {
                 switch(error.code) {
                     case error.PERMISSION_DENIED:
                         alert("User did not share geolocation data");
                         break;

                     case error.POSITION_UNAVAILABLE:
                         alert("Could not detect current position");
                         break;

                     case error.TIMEOUT:
                         alert("Retrieving position timed out");
                         break;

                     default:
                         alert("Unknown Error");
                         break;
                 }
             }

             function normalize_yql_response(response) {
                 if(response.error) {
                     var error = {
                         code : 0
                     };
                     handle_error(error);
                     return;
                 }

                 var position = {
                     coords : {
                         latitude : response.place.centroid.latitude,
                         longitude : response.place.centroid.longitude
                     },
                     address : {
                         city : response.place.locality2.content,
                         region : response.place.admin1.content,
                         country : response.place.country.content
                     }
                 };

                 handle_geolocation_query(position);
             }

             function handle_geolocation_query(position) {
                 jQuery.cookie('geo_latitude', position.coords.latitude);
                 jQuery.cookie('geo_longitude', position.coords.longitude);

                 var image_url = "http://maps.google.com/maps/api/staticmap?sensor=false&center=" + position.coords.latitude + "," + position.coords.longitude + "&zoom=12&size=400x116&style=feature:water|element:geometry|hue:0x336699|saturation:30|lightness:25&style=feature:road.highway|element:labels|visibility:off&style=feature:transit|element:all|visibility:off&markers=icon:http%3A%2F%2Fwww.jabbermap.com%2Fwp-content%2Fuploads%2Fimages%2Fmarker.png|" + position.coords.latitude + ',' + position.coords.longitude;

                 jQuery("#map").remove();
                 jQuery('#welcome_map').append(jQuery(document.createElement("img")).attr("src", image_url).attr('id', 'map'));
             }
            // Find user's location end



            // Slider start: http://www.webchief.co.uk/blog/simple-jquery-slideshow/index.php   
            jQuery(document).ready(function () {

                var currentPosition = 0;
                var slideWidth = 630;
                var slides = jQuery('.slide');
                var numberOfSlides = slides.length;
                var slideShowInterval;
                var speed = 8000;

                slideShowInterval = setInterval(changePosition, speed);
                slides.wrapAll('<div id="slidesHolder"></div>')
                slides.css({ 'float' : 'left' });
                jQuery('#slidesHolder').css('width', slideWidth * numberOfSlides);

                function changePosition() {
                    if(currentPosition == numberOfSlides - 1) {
                        currentPosition = 0;
                    } else {
                        currentPosition++;
                    }
                    moveSlide();
                }

                function moveSlide() {
                    jQuery('#slidesHolder').animate({'marginLeft' : slideWidth*(-currentPosition)});
                }
            });
            // Slider end

2 个答案:

答案 0 :(得分:1)

这是代码......

// Request a position. We only accept cached positions whose age is not
// greater than 10 minutes. If the user agent does not have a fresh
// enough cached position object, it will immediately invoke the error
// callback.
navigator.geolocation.getCurrentPosition(successCallback,
                                         errorCallback,
                                         {maximumAge:600000, timeout:0});

function successCallback(position) {
  // By using the 'maximumAge' option above, the position
  // object is guaranteed to be at most 10 minutes old.
  // By using a 'timeout' of 0 milliseconds, if there is
  // no suitable cached position available, the user agent 
  // will aynchronously invoke the error callback with code
  // TIMEOUT and will not initiate a new position
  // acquisition process.
}

function errorCallback(error) {
  switch(error.code) {
    case error.TIMEOUT:
      // Quick fallback when no suitable cached position exists.
      doFallback();
      // Acquire a new position object.
      navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
      break;
    case ... // treat the other error cases.
  };
}

function doFallback() {
  // No fresh enough cached position available.
  // Fallback to a default position.
}

甚至更好......这里是关于此代码和更多地理定位的文档的链接。

W3 Geolocation API

希望有所帮助!

答案 1 :(得分:-1)

var watchID;

// Obtain the initial location one-off
navigator.geolocation.getCurrentPosition(getPosition);

// Obtain the location at regularly interval<br>
watchID = navigator.geolocation.watchPosition(getPosition);

// Discontinue watch
navigator.geolocation.clearWatch(watchID);

来源:https://www.codingame.com/playgrounds/3799/html-geolocation