下面是使用Lat / long自动完成的代码。 我希望结果特定于一个城市。 我的意思是,自动完成的搜索应限于一个城市。 尽快帮助我..
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>
<script type="text/javascript">
$("#autocomplete").on('focus', function () {
geolocate();
});
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
/** @type {HTMLInputElement} */ (document.getElementById('autocomplete')), {
types: ['geocode']
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
fillInAddress();
});
}
function fillInAddress() {
var place = autocomplete.getPlace();
document.getElementById("latitude").value = place.geometry.location.lat();
document.getElementById("longitude").value = place.geometry.location.lng();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementById("latitude").value = latitude;
document.getElementById("longitude").value = longitude;
autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
});
}
}
initialize();
</script>
</head>
<body onload="initialize()">
<div id="locationField">
<input id="autocomplete" size="60" placeholder="Enter your address" type="text"></input>
</div>
<table id="address">
<tr>
<td class="label">Lat</td>
<td class="slimField">
<input type="text" class="field" id="latitude"></input>
</td>
<td class="label">Long</td>
<td class="wideField">
<input type="text" class="field" id="longitude"></input>
</td>
</tr>
</table>
</body>
</html>
答案 0 :(得分:0)
$.get("http://ipinfo.io", function (response) {
$("#ip").html("IP: " + response.ip);
$("#address").html("Location: " + response.city + ", " + response.region);
$("#details").html(JSON.stringify(response, null, 4));
}, "jsonp");
这是小提琴http://jsfiddle.net/zK5FN/2/,会根据lat和long告诉你这个城市。
它使用ipinfo.io