我有一个包含两个预定义位置的集合,根据用户输入的邮政编码,我需要展示最近的那一个。
目前,我已经使用邮政编码搜索了用户输入的位置。
$("form#zipcodeSearch").on("submit", function(event){
event.preventDefault();
var jsonUrl = 'http://maps.googleapis.com/maps/api/geocode/json?address='+$("input#zipcode").val();
$.ajax({
type: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
},
dataType: "json",
url: jsonUrl,
success: function (data) {
var lat = (data.results[0].geometry.bounds.northeast.lat + data.results[0].geometry.bounds.southwest.lat) / 2;
var lng = (data.results[0].geometry.bounds.northeast.lng + data.results[0].geometry.bounds.southwest.lng) / 2;
initialize(lat, lng);
}
});
});
var map;
function initialize(lat, lng) {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(lat, lng);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: '<div style="width: 75px">You are here!</div>'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
}, {
enableHighAccuracy: true
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
*{
margin: 0;
padding: 0;
}
body{
font-family: arial;
font-size: 62.5%; /* so, 10px = 1rem */
}
#map-canvas{
z-index: -1;
position: absolute;
top: 0;
height: 100%;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<form id="zipcodeSearch">
<input type="text" id="zipcode" placeholder="Enter Zipcode"/>
<input type="submit" value="Search" />
</form>
<div id="map-canvas"></div>
如何实现这个功能?如果使用JS API无法实现,是否有其他API可以帮助我实现?