我正在尝试制作一个需要地址和邮政编码的简单表单,所以我想知道是否有办法根据用户已经键入的内容自动填充这些字段。
因此,例如,如果他决定只输入邮政编码,则城市和国家/地区字段将自动填写,反之亦然。
搜索了一段时间后,我找到了这些我可以使用的数据库
- 链接 1
- 链接 2
但除此之外,我不确定如何使用PHP和MySQL来做到这一点。 任何帮助将不胜感激。
*这很简单,您只需从用户那里获取邮政编码,您就可以使用Google API获取$country和$city。在这里,我给你一个例子,说明我如何从邮政编码(即代码)中获取经度和纬度.zip。
$postcode=$_POST('postcode');
if($postcode)
{
$address = urlencode($postcode);
$url='http://maps.googleapis.com/maps/api/geocode/json?address='.$address.'&sensor=false';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
$source = $data;
$obj = json_decode($source);
$lat = $obj->results[0]->geometry->location->lat;
$long = $obj->results[0]->geometry->location->lng;
}
$longitude=$long;
$latitude=$lat;
您可以在数据库中插入上述两个变量$longitude和$latitude。简单,:).go 转到以下链接 https://developers.google.com/maps/documentation/geocoding/?csw=1
现在要从经度和纬度获取国家/地区名称,请使用反向地理编码。在 latLng 参数中提供逗号分隔的纬度/经度对。
var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
function codeLatLng() {
var input = document.getElementById("latlng").value;
var latlngStr = input.split(",",2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);//here you will get your country and city name
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
在此处阅读有关反向Geocodng的信息,并根据需要修改代码 https://developers.google.com/maps/documentation/javascript/geocoding#ReverseGeocoding
Use : getLocations(latlng:GLatLng, callback:function)
此方法执行反向地理编码,即将纬度/经度对转换为人类可读的地址。 getLocations() 向 Google 地理编码服务发送请求,要求它返回给定 latlng 的地址并在给定回调中传递响应。
由于此方法需要调用 Google 服务器,因此您还必须传递回调方法来处理响应。此响应将包含一个状态代码,如果成功,则包含一个或多个地标对象。
请注意,此方法可能会传递可寻址字符串,如上所述;在这种情况下,服务将执行标准地理编码。但是,如果第一个参数包含 GLatLng,则服务将执行反向地理编码。
执行@RoyalBg sais 的操作,但如果"基于用户已经键入的内容",则应添加一列userid
SELECT zip_code FROM locations WHERE country like '%$country%' and userid = 254