1-如何在谷歌地图中显示带有标记的30状态,每个州有60个城市 2-默认情况下,只有在选择任何状态后才显示带标记的状态,然后用标记显示所有选定状态的城市。
答案 0 :(得分:0)
这很有效。在执行代码之前,请务必更改您的API_KEY
。也请在点击标记之前离开。如果您匆匆点击它们,谷歌会在响应中回复OVER_QUERY_LIMIT
,并且无法设置标记。我只试过了3个州和每个4-6个城市。
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 600px;
width: 50%;
margin:0 auto;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map, geocoder, oldselectedstate="Tamilnadu", selectedstate="Tamilnadu", statemarkers={}, citymarkers={};
var cities = {"Tamilnadu":["Chennai","Namakkal","Madurai","Keeladi","Coimbatore","Kanyakumari"],"Andhra Pradesh":["Visakhapatnam","Vijayawada","Guntur","Nellore","Rajahmundry"],"Kerala":["Trivandrum","Cochin","Calicut","Quilon","Trichur"]};
var states = Object.keys(cities);
function initMap()
{
var nagpur = {lat: 21.146633, lng: 79.088860};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: nagpur
});
geocoder = new google.maps.Geocoder();
createStateMarkers();
createCityMarkers();
}
function toggleMarkers(markers, isshowmarkers)
{
console.log(markers);
for (var i = 0; i < markers.length; i++)
{
markers[i].setMap(isshowmarkers?map:null);
}
}
function toggleCityMarkers(isshowmarkers)
{
toggleMarkers(Object.values(citymarkers[isshowmarkers?selectedstate:oldselectedstate]),isshowmarkers);
}
function createMarker(position, icon, placename)
{
return new google.maps.Marker({
position: position,
map: map,
icon: icon,
customInfo: {name:placename},
});
}
function createCityMarkers()
{
if(!citymarkers[selectedstate])
{
cities[selectedstate].forEach(function(city){
geocoder.geocode({ address: city }, function (results, status) {
if(status === google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
var marker = createMarker({lat:location.lat(),lng:location.lng()}, "http://maps.google.com/mapfiles/ms/icons/blue-dot.png", city);
citymarkers[selectedstate] = citymarkers[selectedstate]||{};
citymarkers[selectedstate][city] = marker;
toggleCityMarkers(false);
}
});
});
}
else
{
toggleCityMarkers(true);
}
}
function createStateMarkers()
{
states.forEach(function(item){
geocoder.geocode({ address: item }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
var marker = createMarker({lat:location.lat(),lng:location.lng()}, "http://maps.google.com/mapfiles/ms/icons/red-dot.png", item);
marker.addListener("click",function(){
oldselectedstate = selectedstate;
toggleCityMarkers(false);
selectedstate = this.customInfo.name;
createCityMarkers();
});
statemarkers[item]=marker;
}
});
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAFTDif2GgY6fxV1wLRjDO9fLGzgM4NRd0&callback=initMap">
</script>
</body>
</html>