james james - 3 months ago 13
jQuery Question

Setting Current User Location for locationpicker.jquery.js

I am using locationpicker.jquery.js and im trying to supply the variables for longitude and latitude before it loads so that the user can load from his or her specific location.

$('.map').locationpicker({
location: {
latitude: 10.621760,
longitude: 121.107015
},
radius: 10,
inputBinding: {
latitudeInput: $('.map-lat'),
longitudeInput: $('.map-lon'),
radiusInput: $('.map-radius'),
locationNameInput: $('.map-address'),
scrollwheel: true
},
enableReverseGeocode: true
});

$( document ).ready(function() {
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
$('.map-lat').val(position.coords.latitude);
$('.map-lon').val(position.coords.longitude);
}
});


I have tried putting jquery selectors and putting them into the variables for latitude and longitude. I have tried setting a hidden input field and passing these to latitude and longitude; but they just fail. Is there something I can do to make locationpicker load at the user's location? latitude and longitude does not seem to accept any other types of variables other than numbers.

Answer

I think the issue you're having is that getCurrentLocation is an asynchronous process. This means that you need to load the map after that process has completed.

$( document ).ready(function() {
  navigator.geolocation.getCurrentPosition(showPosition);
  function showPosition(position) {
      var lat = position.coords.latitude;
      var lng = position.coords.longitude;
      $('.map-lat').val(lat);
      $('.map-lon').val(lng);
      buildMap(lat, lng);
  }
});

Pass in the lat and lng arguments and convert them to a floating-point number (+lat...), otherwise use the defaults.

function buildMap(lat, lng) {
  $('.map').locationpicker({
    location: {
      latitude: +lat || 10.621760,
      longitude: +lng || 121.107015
    },
    radius: 10,
    ...
}