从地理编码器结果获取城市?

发布于 2024-11-15 08:15:53 字数 726 浏览 3 评论 0原文

从地理编码器结果获取不同的数组内容时遇到问题。

item.formatted_address 有效,但 item.address_components.locality 无效?

geocoder.geocode( {'address': request.term }, function(results, status) {

        response($.map(results, function(item) {

        alert(item.formatted_address+" "+item.address_components.locality)
    }            
}); 

// 返回的数组是;

 "results" : [
      {
         "address_components" : [
            {
               "long_name" : "London",
               "short_name" : "London",
               "types" : [ "locality", "political" ]
            } ],
          "formatted_address" : "Westminster, London, UK" // rest of array...

任何帮助表示赞赏!

直流

Having problems getting the different arrays content from geocoder results.

item.formatted_address works but not item.address_components.locality?

geocoder.geocode( {'address': request.term }, function(results, status) {

        response($.map(results, function(item) {

        alert(item.formatted_address+" "+item.address_components.locality)
    }            
}); 

// the array returned is;

 "results" : [
      {
         "address_components" : [
            {
               "long_name" : "London",
               "short_name" : "London",
               "types" : [ "locality", "political" ]
            } ],
          "formatted_address" : "Westminster, London, UK" // rest of array...

any help appreciated!

Dc

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

清风挽心 2024-11-22 08:15:55

我使用了一个名为 find 的 lodash 函数,它返回谓词返回 true 的对象。就这么简单!

let city = find(result, (address) => {
  return typeof find(address.types, (a) => { return a === 'locality'; }) === 'string';
});

I used a lodash function called find which returns the object that the predicate returns true for. As simple as that!

let city = find(result, (address) => {
  return typeof find(address.types, (a) => { return a === 'locality'; }) === 'string';
});
江南月 2024-11-22 08:15:55

好吧,如果你想进入这座城市,这对我有用

var city = "";
function getPositionByLatLang(lat, lng) {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                //formatted address
                city = results[0].plus_code.compound_code;
                city = city.substr(0, city.indexOf(','));
                city = city.split(' ')[1];

                console.log("the name of city is: "+ city);
            }
        } else {
            // alert("Geocoder failed due to: " + status);
        }
    });
}

Well this worked for me if you want to get the city

var city = "";
function getPositionByLatLang(lat, lng) {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                //formatted address
                city = results[0].plus_code.compound_code;
                city = city.substr(0, city.indexOf(','));
                city = city.split(' ')[1];

                console.log("the name of city is: "+ city);
            }
        } else {
            // alert("Geocoder failed due to: " + status);
        }
    });
}
终难愈 2024-11-22 08:15:55

正如大多数答案所说,地址组成部分一直在变化,并且它们因国家/地区而异。您不能仅对地点进行核算,因为在某些地址和区域中这是不可用的。例如,检查印度尼西亚的地点 ID: <代码>EjdOeXVoIEt1bmluZyBSb2FkLCBNQVMsIEdpYW55YXIgUmVnZW5jeSwgQmFsaSwgSW5kb2 5lc2lhIi4qLAoUChIJJzq08aA90i0Rb3AEsy1pPUoSFAoSCcsgYMOTPdItEYAPg8r7CwMF

查找城市的更可靠方法是使用 administrative_area_level 类型。如果未提供位置,则采用较低级别的行政区域(或您喜欢的行政区域),如下所示:

function getAddressComponents(address_components) {

  let address = ''
  let postcode = ''
  let city = ''
  let country = ''
  let country_code = ''
  let postal_code = ''
  let admin_areas: string[] = []

  for (const component of address_components as google.maps.GeocoderAddressComponent[]) {
    const componentType = component.types[0]

    switch (componentType) {
      case 'country':
        country = component.long_name
        country_code = component.short_name
        break
      case 'postal_town':
      case 'locality':
        if (city) {
          city += ', '
        }
        city += component.long_name
        break
      case 'street_number':
      case 'route':
        if (address) {
          address += ', '
        }
        address += component.long_name
        break
      case 'postal_code':
      case 'postal_code_suffix':
        if (postal_code) {
          postal_code += ', '
        }
        postal_code += component.long_name
        break
      default:
        if (componentType.startsWith('administrative_area_level')) {
          admin_areas.push(component.long_name)
        }
    }
  }
  if(!city) {
    city = admin_areas[0]
  }
  return { address, postcode, country, city }
}

As most answers say, the address components change all the time and they vary hugely by country/region. You cannot account just on locality because in some addresses and regions that's not available. As an example, check this place ID here in Indonesia: EjdOeXVoIEt1bmluZyBSb2FkLCBNQVMsIEdpYW55YXIgUmVnZW5jeSwgQmFsaSwgSW5kb25lc2lhIi4qLAoUChIJJzq08aA90i0Rb3AEsy1pPUoSFAoSCcsgYMOTPdItEYAPg8r7CwMF

A more robust way to find the city is to use the administrative_area_level types. If locality is not provided, then take the lower level administrative area (or which one you prefer), like so:

function getAddressComponents(address_components) {

  let address = ''
  let postcode = ''
  let city = ''
  let country = ''
  let country_code = ''
  let postal_code = ''
  let admin_areas: string[] = []

  for (const component of address_components as google.maps.GeocoderAddressComponent[]) {
    const componentType = component.types[0]

    switch (componentType) {
      case 'country':
        country = component.long_name
        country_code = component.short_name
        break
      case 'postal_town':
      case 'locality':
        if (city) {
          city += ', '
        }
        city += component.long_name
        break
      case 'street_number':
      case 'route':
        if (address) {
          address += ', '
        }
        address += component.long_name
        break
      case 'postal_code':
      case 'postal_code_suffix':
        if (postal_code) {
          postal_code += ', '
        }
        postal_code += component.long_name
        break
      default:
        if (componentType.startsWith('administrative_area_level')) {
          admin_areas.push(component.long_name)
        }
    }
  }
  if(!city) {
    city = admin_areas[0]
  }
  return { address, postcode, country, city }
}
吾性傲以野 2024-11-22 08:15:55

无需迭代即可获取城市,通常城市位于address_components对象的第二个键上,因此第二个表示1:

results[0].address_components[1].long_name

You can get the city without iterate, generally the city is located on the 2nd key of address_components object so the 2nd mean 1:

results[0].address_components[1].long_name
姐不稀罕 2024-11-22 08:15:54

最终使用以下方法使此工作正常进行:

var arrAddress = item.address_components;
var itemRoute='';
var itemLocality='';
var itemCountry='';
var itemPc='';
var itemSnumber='';

// iterate through address_component array
$.each(arrAddress, function (i, address_component) {
    console.log('address_component:'+i);

    if (address_component.types[0] == "route"){
        console.log(i+": route:"+address_component.long_name);
        itemRoute = address_component.long_name;
    }

    if (address_component.types[0] == "locality"){
        console.log("town:"+address_component.long_name);
        itemLocality = address_component.long_name;
    }

    if (address_component.types[0] == "country"){ 
        console.log("country:"+address_component.long_name); 
        itemCountry = address_component.long_name;
    }

    if (address_component.types[0] == "postal_code_prefix"){ 
        console.log("pc:"+address_component.long_name);  
        itemPc = address_component.long_name;
    }

    if (address_component.types[0] == "street_number"){ 
        console.log("street_number:"+address_component.long_name);  
        itemSnumber = address_component.long_name;
    }
    //return false; // break the loop   
});

Got this working in the end using:

var arrAddress = item.address_components;
var itemRoute='';
var itemLocality='';
var itemCountry='';
var itemPc='';
var itemSnumber='';

// iterate through address_component array
$.each(arrAddress, function (i, address_component) {
    console.log('address_component:'+i);

    if (address_component.types[0] == "route"){
        console.log(i+": route:"+address_component.long_name);
        itemRoute = address_component.long_name;
    }

    if (address_component.types[0] == "locality"){
        console.log("town:"+address_component.long_name);
        itemLocality = address_component.long_name;
    }

    if (address_component.types[0] == "country"){ 
        console.log("country:"+address_component.long_name); 
        itemCountry = address_component.long_name;
    }

    if (address_component.types[0] == "postal_code_prefix"){ 
        console.log("pc:"+address_component.long_name);  
        itemPc = address_component.long_name;
    }

    if (address_component.types[0] == "street_number"){ 
        console.log("street_number:"+address_component.long_name);  
        itemSnumber = address_component.long_name;
    }
    //return false; // break the loop   
});
旧梦荧光笔 2024-11-22 08:15:54

尝试了几个不同的请求:

MK107BX

<一href="http://maps.googleapis.com/maps/api/geocode/json?address=2a%20Cleveland%20Park%20Crescent,UK&sensor=false" rel="noreferrer">英国克利夫兰公园新月

就像你说的,返回的数组大小不一致,但两个结果的城镇似乎都在类型为 [ "locality", "political" ] 的 address_component 项中。也许你可以用它作为一个指标?

编辑:使用 jQuery 获取位置对象,将其添加到您的响应函数中:

var arrAddress = item.results[0].address_components;
// iterate through address_component array
$.each(arrAddress, function (i, address_component) {
    if (address_component.types[0] == "locality") // locality type
        console.log(address_component.long_name); // here's your town name
        return false; // break the loop
    });

tried a couple of different requests:

MK107BX

Cleveland Park Crescent, UK

like you say, array size returned is inconsistent but the Town for both results appears to be in the address_component item with type of [ "locality", "political" ]. Perhaps you could use that as an indicator?

EDIT: get the locality object using jQuery, add this to your response function:

var arrAddress = item.results[0].address_components;
// iterate through address_component array
$.each(arrAddress, function (i, address_component) {
    if (address_component.types[0] == "locality") // locality type
        console.log(address_component.long_name); // here's your town name
        return false; // break the loop
    });
濫情▎り 2024-11-22 08:15:54

我必须创建一个程序,当用户单击地图上的位置时,该程序将填写用户表单中的纬度、经度、城市、县和州字段。该页面可以在 http://krcproject.groups.et.byu.net 找到,并且是允许公众为数据库做出贡献的用户表单。我不敢自称是专家,但它效果很好。

<script type="text/javascript">
  function initialize() 
  {
    //set initial settings for the map here
    var mapOptions = 
    {
      //set center of map as center for the contiguous US
      center: new google.maps.LatLng(39.828, -98.5795),
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.HYBRID
    };

    //load the map
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);

    //This runs when the user clicks on the map
    google.maps.event.addListener(map, 'click', function(event)
    {
      //initialize geocoder
      var geocoder = new google.maps.Geocoder()

      //load coordinates into the user form
      main_form.latitude.value = event.latLng.lat();
      main_form.longitude.value = event.latLng.lng();

      //prepare latitude and longitude
      var latlng = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());

      //get address info such as city and state from lat and long
      geocoder.geocode({'latLng': latlng}, function(results, status) 
      {
        if (status == google.maps.GeocoderStatus.OK) 
        {
          //break down the three dimensional array into simpler arrays
          for (i = 0 ; i < results.length ; ++i)
          {
            var super_var1 = results[i].address_components;
            for (j = 0 ; j < super_var1.length ; ++j)
            {
              var super_var2 = super_var1[j].types;
              for (k = 0 ; k < super_var2.length ; ++k)
              {
                //find city
                if (super_var2[k] == "locality")
                {
                  //put the city name in the form
                  main_form.city.value = super_var1[j].long_name;
                }
                //find county
                if (super_var2[k] == "administrative_area_level_2")
                {
                  //put the county name in the form
                  main_form.county.value = super_var1[j].long_name;
                }
                //find State
                if (super_var2[k] == "administrative_area_level_1")
                {
                  //put the state abbreviation in the form
                  main_form.state.value = super_var1[j].short_name;
                }
              }
            }
          }
        }
      });
    });
  }
</script>

I had to create a program that would fill in the latitude, longitude, city, county, and state fields in a user form when the user clicks on a location on the map. The page can be found at http://krcproject.groups.et.byu.net and is a user form to allow the public to contribute to a database. I don't claim to be an expert, but it works great.

<script type="text/javascript">
  function initialize() 
  {
    //set initial settings for the map here
    var mapOptions = 
    {
      //set center of map as center for the contiguous US
      center: new google.maps.LatLng(39.828, -98.5795),
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.HYBRID
    };

    //load the map
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);

    //This runs when the user clicks on the map
    google.maps.event.addListener(map, 'click', function(event)
    {
      //initialize geocoder
      var geocoder = new google.maps.Geocoder()

      //load coordinates into the user form
      main_form.latitude.value = event.latLng.lat();
      main_form.longitude.value = event.latLng.lng();

      //prepare latitude and longitude
      var latlng = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());

      //get address info such as city and state from lat and long
      geocoder.geocode({'latLng': latlng}, function(results, status) 
      {
        if (status == google.maps.GeocoderStatus.OK) 
        {
          //break down the three dimensional array into simpler arrays
          for (i = 0 ; i < results.length ; ++i)
          {
            var super_var1 = results[i].address_components;
            for (j = 0 ; j < super_var1.length ; ++j)
            {
              var super_var2 = super_var1[j].types;
              for (k = 0 ; k < super_var2.length ; ++k)
              {
                //find city
                if (super_var2[k] == "locality")
                {
                  //put the city name in the form
                  main_form.city.value = super_var1[j].long_name;
                }
                //find county
                if (super_var2[k] == "administrative_area_level_2")
                {
                  //put the county name in the form
                  main_form.county.value = super_var1[j].long_name;
                }
                //find State
                if (super_var2[k] == "administrative_area_level_1")
                {
                  //put the state abbreviation in the form
                  main_form.state.value = super_var1[j].short_name;
                }
              }
            }
          }
        }
      });
    });
  }
</script>
浅唱々樱花落 2024-11-22 08:15:54

我假设您想要获取城市和州/省:

var map_center = map.getCenter();
reverseGeocode(map_center);


function reverseGeocode(latlng){
  geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
            var level_1;
            var level_2;
            for (var x = 0, length_1 = results.length; x < length_1; x++){
              for (var y = 0, length_2 = results[x].address_components.length; y < length_2; y++){
                  var type = results[x].address_components[y].types[0];
                    if ( type === "administrative_area_level_1") {
                      level_1 = results[x].address_components[y].long_name;
                      if (level_2) break;
                    } else if (type === "locality"){
                      level_2 = results[x].address_components[y].long_name;
                      if (level_1) break;
                    }
                }
            }
            updateAddress(level_2, level_1);
       } 
  });
}

function updateAddress(city, prov){
   // do what you want with the address here
}

不要尝试返回结果,因为您会发现它们是未定义的 - 这是异步服务的结果。您必须调用一个函数,例如 updateAddress();

I am assuming you want to get the city and the state / province:

var map_center = map.getCenter();
reverseGeocode(map_center);


function reverseGeocode(latlng){
  geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
            var level_1;
            var level_2;
            for (var x = 0, length_1 = results.length; x < length_1; x++){
              for (var y = 0, length_2 = results[x].address_components.length; y < length_2; y++){
                  var type = results[x].address_components[y].types[0];
                    if ( type === "administrative_area_level_1") {
                      level_1 = results[x].address_components[y].long_name;
                      if (level_2) break;
                    } else if (type === "locality"){
                      level_2 = results[x].address_components[y].long_name;
                      if (level_1) break;
                    }
                }
            }
            updateAddress(level_2, level_1);
       } 
  });
}

function updateAddress(city, prov){
   // do what you want with the address here
}

Don't try to return the results as you will find that they are undefined - a result of an asynchronous service. You must call a function, such as updateAddress();

权谋诡计 2024-11-22 08:15:54

我创建了这个函数来获取地理编码器结果的主要信息:

const getDataFromGeoCoderResult = (geoCoderResponse) => {
  const geoCoderResponseHead = geoCoderResponse[0];
  const geoCoderData = geoCoderResponseHead.address_components;
  const isEmptyData = !geoCoderResponseHead || !geoCoderData;

  if (isEmptyData) return {};

  return geoCoderData.reduce((acc, { types, long_name: value }) => {
    const type = types[0];

    switch (type) {
      case 'route':
        return { ...acc, route: value };
      case 'locality':
        return { ...acc, locality: value };
      case 'country':
        return { ...acc, country: value };
      case 'postal_code_prefix':
        return { ...acc, postalCodePrefix: value };
      case 'street_number':
        return { ...acc, streetNumber: value };
      default:
        return acc;
    }
  }, {});
};

因此,您可以像这样使用它:

const geoCoderResponse = await geocodeByAddress(value);
const geoCoderData = getDataFromGeoCoderResult(geoCoderResponse);

假设您要搜索圣地亚哥伯纳乌体育场,所以结果将是:

{
  country: 'Spain',
  locality: 'Madrid',
  route: 'Avenida de Concha Espina',
  streetNumber: '1',
}

I created this function to get the main info of geocoder results:

const getDataFromGeoCoderResult = (geoCoderResponse) => {
  const geoCoderResponseHead = geoCoderResponse[0];
  const geoCoderData = geoCoderResponseHead.address_components;
  const isEmptyData = !geoCoderResponseHead || !geoCoderData;

  if (isEmptyData) return {};

  return geoCoderData.reduce((acc, { types, long_name: value }) => {
    const type = types[0];

    switch (type) {
      case 'route':
        return { ...acc, route: value };
      case 'locality':
        return { ...acc, locality: value };
      case 'country':
        return { ...acc, country: value };
      case 'postal_code_prefix':
        return { ...acc, postalCodePrefix: value };
      case 'street_number':
        return { ...acc, streetNumber: value };
      default:
        return acc;
    }
  }, {});
};

So, you can use it like this:

const geoCoderResponse = await geocodeByAddress(value);
const geoCoderData = getDataFromGeoCoderResult(geoCoderResponse);

let's say that you are going search Santiago Bernabéu Stadium, so, the result will be:

{
  country: 'Spain',
  locality: 'Madrid',
  route: 'Avenida de Concha Espina',
  streetNumber: '1',
}
╭ゆ眷念 2024-11-22 08:15:54

这对我有用:

const localityObject = body.results[0].address_components.filter((obj) => {
  return obj.types.includes('locality');
})[0];
const city = localityObject.long_name;

或者一次性:

const city = body.results[0].address_components.filter((obj) => {
  return obj.types.includes('locality');
)[0].long_name;

我在 Node 中执行此操作,所以这没问题。如果您需要支持 IE,则需要使用 Array.prototype.includes 或找到另一种方法。

This worked for me:

const localityObject = body.results[0].address_components.filter((obj) => {
  return obj.types.includes('locality');
})[0];
const city = localityObject.long_name;

or in one go:

const city = body.results[0].address_components.filter((obj) => {
  return obj.types.includes('locality');
)[0].long_name;

I'm doing this in Node, so this is okay. If you need to support IE you need to use a polyfill for Array.prototype.includes or find another way of doing it.

假情假意假温柔 2024-11-22 08:15:54

我认为谷歌不提供某种功能来获取这些内容真是令人痛苦。无论如何,我认为找到合适对象的最佳方法是:

geocoder.geocode({'address': request.term }, function(results, status){

   response($.map(results, function(item){

      var city = $.grep(item.address_components, function(x){
         return $.inArray('locality', x.types) != -1;
      })[0].short_name;

      alert(city);
   }            
}); 

I think it is a real pain that google doesn't provide some sort of functionality to get these. Anyhow I think the best way of finding the right object is:

geocoder.geocode({'address': request.term }, function(results, status){

   response($.map(results, function(item){

      var city = $.grep(item.address_components, function(x){
         return $.inArray('locality', x.types) != -1;
      })[0].short_name;

      alert(city);
   }            
}); 
醉生梦死 2024-11-22 08:15:54
// Use Google Geocoder to get Lat/Lon for Address
function codeAddress() {
    // Function geocodes address1 in the Edit Panel and fills in lat and lon
    address = document.getElementById("tbAddress").value;
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            loc[0] = results[0].geometry.location.lat();
            loc[1] = results[0].geometry.location.lng();
            document.getElementById("tbLat").value = loc[0];
            document.getElementById("tbLon").value = loc[1];
            var arrAddress = results[0].address_components;
            for (ac = 0; ac < arrAddress.length; ac++) {
                if (arrAddress[ac].types[0] == "street_number") { document.getElementById("tbUnit").value = arrAddress[ac].long_name }
                if (arrAddress[ac].types[0] == "route") { document.getElementById("tbStreet").value = arrAddress[ac].short_name }
                if (arrAddress[ac].types[0] == "locality") { document.getElementById("tbCity").value = arrAddress[ac].long_name }
                if (arrAddress[ac].types[0] == "administrative_area_level_1") { document.getElementById("tbState").value = arrAddress[ac].short_name }
                if (arrAddress[ac].types[0] == "postal_code") { document.getElementById("tbZip").value = arrAddress[ac].long_name }
            }
            document.getElementById("tbAddress").value = results[0].formatted_address;
        }
        document.getElementById("pResult").innerHTML = 'GeoCode Status:' + status;
    })
}
// Use Google Geocoder to get Lat/Lon for Address
function codeAddress() {
    // Function geocodes address1 in the Edit Panel and fills in lat and lon
    address = document.getElementById("tbAddress").value;
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            loc[0] = results[0].geometry.location.lat();
            loc[1] = results[0].geometry.location.lng();
            document.getElementById("tbLat").value = loc[0];
            document.getElementById("tbLon").value = loc[1];
            var arrAddress = results[0].address_components;
            for (ac = 0; ac < arrAddress.length; ac++) {
                if (arrAddress[ac].types[0] == "street_number") { document.getElementById("tbUnit").value = arrAddress[ac].long_name }
                if (arrAddress[ac].types[0] == "route") { document.getElementById("tbStreet").value = arrAddress[ac].short_name }
                if (arrAddress[ac].types[0] == "locality") { document.getElementById("tbCity").value = arrAddress[ac].long_name }
                if (arrAddress[ac].types[0] == "administrative_area_level_1") { document.getElementById("tbState").value = arrAddress[ac].short_name }
                if (arrAddress[ac].types[0] == "postal_code") { document.getElementById("tbZip").value = arrAddress[ac].long_name }
            }
            document.getElementById("tbAddress").value = results[0].formatted_address;
        }
        document.getElementById("pResult").innerHTML = 'GeoCode Status:' + status;
    })
}
甜妞爱困 2024-11-22 08:15:54

如果存在则返回局部性。如果不是 - 返回administrative_area_1

city = results[0].address_components.filter(function(addr){
   return (addr.types[0]=='locality')?1:(addr.types[0]=='administrative_area_level_1')?1:0;
});

Returns locality if exist. If not - returns administrative_area_1

city = results[0].address_components.filter(function(addr){
   return (addr.types[0]=='locality')?1:(addr.types[0]=='administrative_area_level_1')?1:0;
});
放低过去 2024-11-22 08:15:54
            //if (arrAddress[ac].types[0] == "street_number") { alert(arrAddress[ac].long_name) } // SOKAK NO
            //if (arrAddress[ac].types[0] == "route") { alert(arrAddress[ac].short_name); } // CADDE
            //if (arrAddress[ac].types[0] == "locality") { alert(arrAddress[ac].long_name) } // İL
            //if (arrAddress[ac].types[0] == "administrative_area_level_1") { alert(arrAddress[ac].short_name) } // İL
            //if (arrAddress[ac].types[0] == "postal_code") { alert(arrAddress[ac].long_name); } // POSTA KODU
            //if (arrAddress[ac].types[0] == "neighborhood") { alert(arrAddress[ac].long_name); } // Mahalle
            //if (arrAddress[ac].types[0] == "sublocality") { alert(arrAddress[ac].long_name); } // İlçe
            //if (arrAddress[ac].types[0] == "country") { alert(arrAddress[ac].long_name); } // Ülke
            //if (arrAddress[ac].types[0] == "street_number") { alert(arrAddress[ac].long_name) } // SOKAK NO
            //if (arrAddress[ac].types[0] == "route") { alert(arrAddress[ac].short_name); } // CADDE
            //if (arrAddress[ac].types[0] == "locality") { alert(arrAddress[ac].long_name) } // İL
            //if (arrAddress[ac].types[0] == "administrative_area_level_1") { alert(arrAddress[ac].short_name) } // İL
            //if (arrAddress[ac].types[0] == "postal_code") { alert(arrAddress[ac].long_name); } // POSTA KODU
            //if (arrAddress[ac].types[0] == "neighborhood") { alert(arrAddress[ac].long_name); } // Mahalle
            //if (arrAddress[ac].types[0] == "sublocality") { alert(arrAddress[ac].long_name); } // İlçe
            //if (arrAddress[ac].types[0] == "country") { alert(arrAddress[ac].long_name); } // Ülke
烟花易冷人易散 2024-11-22 08:15:54

以下是一些可以与 lodash js 库一起使用的代码:(只需将 $scope.x 替换为您自己的变量名即可存储值)

    _.findKey(vObj.address_components, function(component) {

            if (component.types[0] == 'street_number') {
                $scope.eventDetail.location.address = component.short_name
            }

            if (component.types[0] == 'route') {
                $scope.eventDetail.location.address = $scope.eventDetail.location.address + " " + component.short_name;
            }

            if (component.types[0] == 'locality') {
                $scope.eventDetail.location.city = component.long_name;
            }

            if (component.types[0] == 'neighborhood') {
                $scope.eventDetail.location.neighborhood = component.long_name;
            }

        });

Here's some code you can use with the lodash js library: (just replace the $scope.x with your own variable name to store the value)

    _.findKey(vObj.address_components, function(component) {

            if (component.types[0] == 'street_number') {
                $scope.eventDetail.location.address = component.short_name
            }

            if (component.types[0] == 'route') {
                $scope.eventDetail.location.address = $scope.eventDetail.location.address + " " + component.short_name;
            }

            if (component.types[0] == 'locality') {
                $scope.eventDetail.location.city = component.long_name;
            }

            if (component.types[0] == 'neighborhood') {
                $scope.eventDetail.location.neighborhood = component.long_name;
            }

        });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文