您需要使用谷歌地图的Geocoder library。它可以将邮编和城镇对解析为地图位置。
我添加了国家元素以获得更准确的结果。
在此示例中,您可以使用邮政编码创建标记。您应该添加更多代码以显示数据集上每个邮政编码的值。
HTML
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<div id="map_div" style="height: 400px;"></div>
JS
/*
* declare map as a global variable
*/
var map;
/*
* use google maps api built-in mechanism to attach dom events
*/
google.maps.event.addDomListener(window, "load", function () {
/*
* create map
*/
var map = new google.maps.Map(document.getElementById("map_div"), {
center: new google.maps.LatLng(35.38905, -40.078125),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
/*
* create infowindow (which will be used by markers)
*/
var infoWindow = new google.maps.InfoWindow();
/*
* marker creater function (acts as a closure for html parameter)
*/
function createMarker(options, html) {
var marker = new google.maps.Marker(options);
if (html) {
google.maps.event.addListener(marker, "click", function () {
infoWindow.setContent(html);
infoWindow.open(options.map, this);
});
}
return marker;
}
function createMarkerZip( zipcode, town, country ) {
var direction = zipcode + ','+town+','+country;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': direction},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
createMarker({
position: new google.maps.LatLng(
results[0].geometry.location.lat(),
results[0].geometry.location.lng()),
map: map
}, direction);
} else {
console.log( "Zip: " + zipcode + ", town: " + town + " not found :-(");
}
}
);
}
createMarkerZip('46003', 'valencia', 'spain');
createMarkerZip("nv 89821", "crescent valley", "usa");
createMarkerZip("va 22310", "alexandria", "usa");
});
https://jsfiddle.net/netvicious/4m2vf0dh/
注意:在 jsfiddle 上,您应该添加您的密钥以使其工作。