简体   繁体   中英

Get a Geo Location to propagate an input

I'm working with a google api for getting the users location and haveing a couple of problems with it. It gives me the exact location, which is the first problem, and secondly i cant get it to write itself into an Input area.

I want it to just get the Town/City rather than house number, street and county etc... and once that has been established propagate the Keyword input.

Can anyone advise how to do this?

Here is the Script:

   function displayLocation(latitude,longitude){
        var request = new XMLHttpRequest();

        var method = 'GET';
        var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true';
        var async = true;

        request.open(method, url, async);
        request.onreadystatechange = function(){
          if(request.readyState == 4 && request.status == 200){
            var data = JSON.parse(request.responseText);
            var address = data.results[0];
            document.write(address.formatted_address);
          }
        };
        request.send();
      };

      var successCallback = function(position){
        var x = position.coords.latitude;
        var y = position.coords.longitude;
        displayLocation(x,y);
      };

      var errorCallback = function(error){
        var errorMessage = 'Unknown error';
        switch(error.code) {
          case 1:
            errorMessage = 'Permission denied';
            break;
          case 2:
            errorMessage = 'Position unavailable';
            break;
          case 3:
            errorMessage = 'Timeout';
            break;
        }
        document.write(errorMessage);
      };

      var options = {
        enableHighAccuracy: true,
        timeout: 1000,
        maximumAge: 0
      };

      navigator.geolocation.getCurrentPosition(successCallback,errorCallback,options);

I believe the specific line for propagating it into the input would be this one:

    document.write(address.formatted_address);

I cant seem to get this to work:

document.getElementById('keyword').innerHTML=(address.formatted_address);

Here is the Fiddle

Ok figured it. The line was:

      document.getElementById("keyword").value = address.formatted_address;

heres the full script FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM