2011-11-16 36 views
9

Tôi đang sử dụng sau đây để có được một sự lat-lng từ một mã địa lý ..Làm thế nào để giải nén Mã bưu chính từ V3 Google Maps API

$latitude = $output->results[0]->geometry->location->lat; 
    $longitude = $output->results[0]->geometry->location->lng; 

Làm thế nào để trích xuất mã bưu chính từ ...

{ 
    "status": "OK", 
    "results": [ { 
    "types": [ "street_address" ], 
    "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA", 
    "address_components": [ { 
     "long_name": "1600", 
     "short_name": "1600", 
     "types": [ "street_number" ] 
    }, { 
     "long_name": "Amphitheatre Pkwy", 
     "short_name": "Amphitheatre Pkwy", 
     "types": [ "route" ] 
    }, { 
     "long_name": "Mountain View", 
     "short_name": "Mountain View", 
     "types": [ "locality", "political" ] 
    }, { 
     "long_name": "California", 
     "short_name": "CA", 
     "types": [ "administrative_area_level_1", "political" ] 
    }, { 
     "long_name": "United States", 
     "short_name": "US", 
     "types": [ "country", "political" ] 
    }, { 
     "long_name": "94043", 
     "short_name": "94043", 
     "types": [ "postal_code" ] 
    } ], 
    "geometry": { 
     "location": { 
     "lat": 37.4219720, 
     "lng": -122.0841430 
     }, 
     "location_type": "ROOFTOP", 
     "viewport": { 
     "southwest": { 
      "lat": 37.4188244, 
      "lng": -122.0872906 
     }, 
     "northeast": { 
      "lat": 37.4251196, 
      "lng": -122.0809954 
     } 
     } 
    } 
    } ] 
} 

Trả lời

0

Tôi muốn nói bạn cần lặp qua results.address_components. Trên mỗi lần kiểm tra lặp lại nếu mảng kiểu chứa "postal_code". Nếu có, lưu nó vào một biến, và có thể thoát ra khỏi vòng lặp là tốt. Mặc dù có thể đáng để điều tra xem mã bưu điện có luôn nằm trong address_component [5] hay không, điều này sẽ giúp bạn tiết kiệm thời gian lặp lại.

13

Bạn có thể sử dụng chức năng sau đây để trích xuất bất kỳ thành phần địa chỉ:

function extractFromAdress(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 ""; 
} 

Để trích xuất mã bưu chính bạn gọi:

extractFromAdress(results[0].address_components, "postal_code"); 

Nhưng bạn cũng có thể nhận được thông tin thú vị khác như:

extractFromAdress(results[0].address_components, "route"); 
extractFromAdress(results[0].address_components, "locality"); 
extractFromAdress(results[0].address_components, "country"); 

vv ...

+0

cảm ơn, tôi đã tự hỏi làm thế nào để làm điều đó trong một thời gian – Francesco

Các vấn đề liên quan