2013-02-21 58 views
1

理想情况下,使用Google API而不是JavaScript hack抓住逗号前的所有内容,我想知道是否可以抓取地址的第一位。这是我使用的代码:从谷歌地图抓取第一个地址段

http://jsfiddle.net/Xw4ZM/3/

var geocoder; 
var map; 
var marker; 

function initialize(){ 
//MAP 
    var latlng = new google.maps.LatLng(41.659,-4.714); 
    var options = { 
    zoom: 16, 
    center: latlng, 
    mapTypeId: google.maps.MapTypeId.SATELLITE 
    }; 

    map = new google.maps.Map(document.getElementById("map_canvas"), options); 

    //GEOCODER 
    geocoder = new google.maps.Geocoder(); 

    marker = new google.maps.Marker({ 
    map: map, 
    draggable: true 
    }); 

} 

$(document).ready(function() { 

    initialize(); 

    $(function() { 
    $("#address").autocomplete({ 
     //This bit uses the geocoder to fetch address values 
     source: function(request, response) { 
     geocoder.geocode({'address': request.term }, function(results, status) { 
      response($.map(results, function(item) { 
      return { 
       label: item.formatted_address, 
       value: item.formatted_address, 
       latitude: item.geometry.location.lat(), 
       longitude: item.geometry.location.lng() 
      } 
      })); 
     }) 
     }, 
     //This bit is executed upon selection of an address 
     select: function(event, ui) { 
     $("#latitude").val(ui.item.latitude); 
     $("#longitude").val(ui.item.longitude); 
     var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude); 
     marker.setPosition(location); 
     map.setCenter(location); 
     } 
    }); 
    }); 

    //Add listener to marker for reverse geocoding 
    google.maps.event.addListener(marker, 'drag', function() { 
    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     if (results[0]) { 
      $('#address').val(results[0].formatted_address); 
      $('#latitude').val(marker.getPosition().lat()); 
      $('#longitude').val(marker.getPosition().lng()); 
     } 
     } 
    }); 
    }); 

}); 

这是我想达到scenaio,如果用户输入这样的:

Swindon, Wiltshire, United Kingdom 
The "name" value is this: "Swindon" 

Wiltshire, United Kingdom: 
The "name" value is this "Wiltshire" 

United Kingdom: 
The "name" value is this "United Kingdom" 

它基本上是保存最准确的位置在名称字段中提供,无论是城镇,县或国家。

回答

0

不确定它是否可以帮助您解决您的情况,但地址搜索结果对象中包含地址组件。

https://developers.google.com/maps/documentation/geocoding/#JSON

geocoder.geocode({ 
     'address': request.term 
    }, function (results, status) { 
     for (i in results) { 
      var result = results[i]; 

      for (j in result.address_components) { 
       var segment = result.address_components[j]; 

       // do something with address segment 
      } 
     } 
    }) 

geocoder.geocode({ 
    'address': request.term 
}, function (results, status) { 
    $.each(results, function (i, result) { 
     $.each(result.address_components, function (i, segment) { 
      // do something with address segment 
     }); 
    }); 
})