properly format postal address with line breaks [google maps]
- by munchybunch
Using V3 of the google maps API, is there any reliable way to format addresses with the line break? By this, I mean something like 1600 Amphitheatre Parkway Mountain View, CA 94043 should be formatted as
1600 Amphitheatre Parkway
Mountain View, CA 94043
Looking through the response object from geocoding, there is an address_components array that has, for the above address, 8 components (not all of the components are used for the address):
0: Object
long_name: "1600"
short_name: "1600"
types: Array[1]
0: "street_number"
length: 1
1: Object
long_name: "Amphitheatre Pkwy"
short_name: "Amphitheatre Pkwy"
types: Array[1]
0: "route"
length: 1
2: Object
long_name: "Mountain View"
short_name: "Mountain View"
types: Array[2]
0: "locality"
1: "political"
length: 2
3: Object
long_name: "San Jose"
short_name: "San Jose"
types: Array[2]
0: "administrative_area_level_3"
1: "political"
length: 2
4: Object
long_name: "Santa Clara"
short_name: "Santa Clara"
types: Array[2]
0: "administrative_area_level_2"
1: "political"
length: 2
5: Object
long_name: "California"
short_name: "CA"
types: Array[2]
0: "administrative_area_level_1"
1: "political"
length: 2
6: Object
long_name: "United States"
short_name: "US"
types: Array[2]
0: "country"
1: "political"
length: 2
7: Object
long_name: "94043"
short_name: "94043"
types: Array[1]
0: "postal_code"
length: 1
I was thinking that you could just combine parts that you want, like
sprintf("%s %s<br />%s, %s %s",
array[0].short_name,
array[1].short_name,
array[2].short_name,
array[5].short_name,
array[7].short_name)
[edit]I just realized that sprintf isn't defined by default in JavaScript, so just a concatenation would do I guess.[/edit]
But that seems awfully unreliable. Does anyone know the details on the structure of address_components, and if it's reliably similar like that for street addresses in the US? If I wanted to, I guess I could look for the proper types (street_number,route, etc) as well.
I'd love it if anyone had a better way than what I"m doing here...