地理代码和国家代码
Geocoder and Country Codes
我正试图将以下脚本发送到Alert或Console。记录国家代码,但它一直给我完整的地址。
有人能帮我一下吗?
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[2].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
您的代码实际上会发出两次警报。第一次格式化地址,第二次格式化国家。
对于第二个警报-将administrative_area_level_1
更改为country
-
if (results[0].address_components[i].types[b] == "country") {
然后,如果你提醒short_name
,你会得到国家代码。
相关文章:
- 如何使用npm国家代码
- 地理代码和国家代码
- 使用从forEach循环中提取的国家代码从数组中获取国家名称
- 谷歌地图,基于国家代码可视化国家
- Ionic Framework如何为带有国家代码的手机号码添加表单
- 如何制作验证电话号码中国家/地区代码的正则表达式
- 如何读取钛合金中的当地国家/地区电话代码xml
- 正则表达式 - 使用可选国家/地区代码验证手机
- 在 JavaScript 中通过给定的电话号码检测国家/地区代码
- 根据国家/地区代码设置电话号码的格式
- jQuery 表单验证,仅允许 .EDU 和 .edu.nn(其中 nn 是 2 位国家/地区代码)电子邮件地址
- 如何在国家/地区代码后删除 0
- 使用jQuery在电话输入字段中插入国家代码
- 通过国家代码jquery获取时区
- 根据用户从下拉列表中选择的内容显示国家/地区代码
- 仅当访问者来自特定国家/地区时才显示javascript代码
- 将两个字母的国家代码与预定义的国家代码数组相匹配
- 使用HTML和Javascript查找三个字母的国家代码
- 如何从Google Places API获取国家代码
- 如何使用地理位置而不是完整的国家和地区名称来获取国家和地区代码