我想从地址组件中获取Google地图place_id
,但我不确定是否可行。我目前有以下代码:
// Extract From Address Function
function extractFromAddress(components, type){
for (var i=0; i<components.length; i++)
for (var j=0; j<components[i].types.length; j++)
if (components[i].types[j]==type) return components[i].long_name;
return "";
}
// Variables
var varMap, varMapOptions, varMapDefaultLatLng, varInput, varAutocompleteOptions;
var varDefaultBounds, varAutocomplete, varMarker, varPlace, varInfoWindow, varInfoWindowContent;
var varPlaceID, varPlaceTitle, varPlaceACSZ;
var varInputText, varInputLength;
// Map Listener
google.maps.event.addListener(varAutocomplete, "place_changed", function() {
// Set Map
varInfoWindow.close();
varMarker.setVisible(false);
// Autocomplete
varPlace = varAutocomplete.getPlace();
// Check for geometry
if (!varPlace.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (varPlace.geometry.viewport) {
varMap.fitBounds(varPlace.geometry.viewport);
} else {
varMap.setCenter(varPlace.geometry.location);
varMap.setZoom(17); // Why 17? Because it looks good.
}
// Set Marker Icon
google.maps.event.addListener(varMap, "click", function(event) {
varMarker.setPosition(event.latLng);
});
// Marker Position
varMarker.setPosition(varPlace.geometry.location);
varMarker.setVisible(true);
// Obtain Address Components
if (varPlace.address_components) {
var varPlaceID = extractFromAddress(varPlace.address_components, "place_id"); // Currently doesn't return a value
var varStreetNumbers = extractFromAddress(varPlace.address_components, "street_number");
var varStreetName = extractFromAddress(varPlace.address_components, "route");
var varCity = extractFromAddress(varPlace.address_components, "locality");
var varState = extractFromAddress(varPlace.address_components, "administrative_area_level_1");
var varPostCode = extractFromAddress(varPlace.address_components, "postal_code");
}
// Assign Address Components
varGooglePlaceID = varPlaceID;
varPlaceTitle = varPlace.name;
varPlaceAddress = varStreetNumbers + ' ' + varStreetName;
varPlaceACSZ = varPlaceAddress + '<br>' + varCity + ', ' + varState + ' ' + varPostCode;
varPlaceLatitude = varPlace.geometry.location.lat();
varPlaceLongitude = varPlace.geometry.location.lng();
这将生成除varPlaceID
变量之外的所有值。我不确定是否可以从place_id
或以其他方式获取address_components
。
感谢您的帮助。 :)
答案 0 :(得分:1)
Demo试试这个,
var varPlaceID = varPlace.place_id;
检查您的street_number
路径varPlace.address_components street_number
"result" : {
"address_components" : [
{
"long_name" : "48",
"short_name" : "48",
"types" : [ "street_number" ]
} // I deleted Other
],
"place_id" : "ChIJN1t_tDeuEmsRUsoyG83frY4"
只需按此varPlace.place_id
,