Skip to content Skip to sidebar Skip to footer

Geolocation: Filling Forms With Latitude And Longitude. Google Maps Api

I've been building a google map where users share information plus their current location in a form. I want to automatically fill the lat, lng fields in my form with the Geolocatio

Solution 1:

You can try this code instead :

navigator.geolocation.getCurrentPosition(function(position) {

  var pos = new google.maps.LatLng(position.coords.latitude,
                                   position.coords.longitude);
  document.getElementById('lat').value = position.coords.latitude;
  document.getElementById('lng').value = position.coords.longitude;    
  var marker = new google.maps.Marker({
    map: map,
    position: pos,
    title: 'GPS'
  });

  map.setCenter(pos);
}, function() {
  handleNoGeolocation(true);
});

it's better to put your javascript code before the </body> tag

Solution 2:

You only have the code to put the values in your form in the error path, put code in the success path instead (I'm not sure what you expect the 'GPS' event you have on the marker to do):

functioninitialize() {
    var mapOptions = {
        zoom: 12
    };
    map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            $('#lat').val(position.coords.latitude);
            $('#lng').val(position.coords.longitude);            
            var pos = new google.maps.LatLng(position.coords.latitude,
            position.coords.longitude);

            var marker = new google.maps.Marker({
                map: map,
                position: pos,
                title: 'GPS'
            });

            map.setCenter(pos);

        }, function () {
            handleNoGeolocation(true);
        });
    } else {

        handleNoGeolocation(false);
    }
}

Post a Comment for "Geolocation: Filling Forms With Latitude And Longitude. Google Maps Api"