javascript – 如何从手机间隙的纬度和经度获取城市名称?

前端之家收集整理的这篇文章主要介绍了javascript – 如何从手机间隙的纬度和经度获取城市名称?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以从当前纬度和经度得到完整的地址.但是如何才能从完整地址获取城市名称.这是我的代码.
  1. var geocoder;
  2. geocoder = new google.maps.Geocoder();
  3. var latlng = new google.maps.LatLng(latitude,longitude);
  4. //alert("Else loop" + latlng);
  5. geocoder.geocode({
  6. 'latLng': latlng
  7. },function(results,status) {
  8. //alert("Else loop1");
  9. if (status == google.maps.GeocoderStatus.OK) {
  10. if (results[0]) {
  11. var add = results[0].formatted_address;
  12. alert("Full address is: " + add);
  13. } else {
  14. alert("address not found");
  15. }
  16. } else {
  17. //document.getElementById("location").innerHTML="Geocoder Failed due to: " + status;
  18. //alert("Geocoder Failed due to: " + status);
  19. }
  20. });

解决方法

  1. var geocoder;
  2. geocoder = new google.maps.Geocoder();
  3. var latlng = new google.maps.LatLng(latitude,longitude);
  4.  
  5. geocoder.geocode(
  6. {'latLng': latlng},status) {
  7. if (status == google.maps.GeocoderStatus.OK) {
  8. if (results[0]) {
  9. var add= results[0].formatted_address ;
  10. var value=add.split(",");
  11.  
  12. count=value.length;
  13. country=value[count-1];
  14. state=value[count-2];
  15. city=value[count-3];
  16. alert("city name is: " + city);
  17. }
  18. else {
  19. alert("address not found");
  20. }
  21. }
  22. else {
  23. alert("Geocoder Failed due to: " + status);
  24. }
  25. }
  26. );

用“,”作为分隔符分割完整地址并获取城市名称.

猜你在找的JavaScript相关文章