如何使用地理位置API获取城市名称和州名?

时间:2017-02-01 09:52:09

标签: javascript javascript-events geolocation

我只是想知道它应该是一个可重复使用的代码,可以使用地理位置检测当前的城市

2 个答案:

答案 0 :(得分:1)

我创建了一个例子:

var city, state;
var geocoder;
if (navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}

//Get the latitude and the longitude;
function successFunction(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  codeLatLng(lat, lng);
}

function errorFunction() {
  console.log("Geocoder failed");
}

function codeLatLng(lat, lng) {
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({
    'latLng': latlng
  }, function(results, status) {
   if (status == google.maps.GeocoderStatus.OK) {
     if (results[1]) {
    //find country name
     for (var i = 0; i < results[0].address_components.length; i++) {
       for (var b = 0; b < results[0].address_components[i].types.length; b++) {
        //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
        if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
          //this is the object you are looking for
          city = results[0].address_components[i];
          break;
        }
      }
    }

    for (var i = 0; i < results[0].address_components.length; i++) {
      for (var b = 0; b < results[0].address_components[i].types.length; b++) {
        //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
        if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
          //this is the object you are looking for
          state = results[0].address_components[i];
          break;
        }
      }
    }
     alert(city.long_name +", "+ state.long_name);
   } else {
     console.log("City name not available");
    }
   } else {
     console.log("Geocoder failed due to: ", status);
   }
  });
}

function initialize() {
  geocoder = new google.maps.Geocoder();
}

document.addEventListener('DOMContentLoaded', function() {
  initialize();
}, false);

可在此Plnkr

找到工作演示

答案 1 :(得分:0)

var x, lat, lng, city, state, country, geocoder, latlng;

$(document).ready(function() {
  getLocation();
});

x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  lat = position.coords.latitude;
  lng = position.coords.longitude;
  // inprange = parseInt($('#range_3').prop("value") * 1000);
  geocodeLatLng(lat, lng);
}

function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "User denied the request for Geolocation.";
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML = "Location information is unavailable.";
      break;
    case error.TIMEOUT:
      x.innerHTML = "The request to get user location timed out.";
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML = "An unknown error occurred.";
      break;
  }
}

function geocodeLatLng(lat, lng) {
  geocoder = new google.maps.Geocoder();
  latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({
    'latLng': latlng
  }, function(results, status) {
    if (status === 'OK') {
      if (results[1]) {
        console.log(results);
        for (var i = 0; i < results[0].address_components.length; i++ ) {
          for (var b = 0; b < results[0].address_components[i].types.length; b++) {
            switch (results[0].address_components[i].types[b]) {
              case 'locality':
                city = results[0].address_components[i].long_name;
                break;
              case 'administrative_area_level_1':
                state = results[0].address_components[i].long_name;
                break;
              case 'country':
                country = results[0].address_components[i].long_name;
                break;
            }
          }
        }
        x.innerHTML = 'City = ' + city + ', ' + 'State = ' + state + ', ' + 'Country = ' + country;
      } else {
        alert("No results found");
      }
    } else {
      alert("Geocoder failed due to: " + status);
    }
  });
}