简体   繁体   中英

Zoom in to Google Marker from Dropdown Menu

I am trying to create a world map with markers. I want a dropdown list and when you click a country name the map zooms to the country where a marker has been placed. I did a Google search and found this question: Google Maps API dropdown list, zoom to marker which is basically what I am looking for. I tried to edit it but it's not working. I don't want info windows, just the name of the country when you hover over each marker. I am also making my own markers. I have also added a 'Your Location' feature which I am using for the center of the map. I would like to include that in the dropdown menu which when clicked it centers the map back to the original position. Once I get it to work, I should be able to add every country in the world. Any ideas of what I'm doing wrong and how to make it work?

The Javascript:

function findYou(){
    if(navigator.geolocation.getCurrentPosition(showPosition, noLocation, {maximumAge : 1200000, timeout : 30000})){
    }
     else{
        document.getElementById("lat").innerHTML="This browser does not support geolocation.";
    }
    }
    function showPosition(location){
        var latitude = location.coords.latitude;
        var longitude = location.coords.longitude;
        var accuracy = location.coords.accuracy;
        var position = new google.maps.LatLng(latitude, longitude);
        var myOptions = {
            zoom:2,
            center: position,
            mapTypeControl: true,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
            zoomControl: true,
            zoomControlOptions: {
                style: google.maps.ZoomControlStyle.SMALL }
  }
        var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

    var homeIcon = 'YourLocation.png';
    var point = new google.maps.Marker({
        icon: homeIcon,
        position: position,
        map: map,
        title:"Your Location"
    });
    markers[1] = UnitedStatesMarker;

    var myLatLng = new google.maps.LatLng(38.907192, -77.036871);
    var UnitedStatesMarker = new google.maps.Marker({
        position: myLatLng,
        icon: src = 'UnitedStates.png',
        map: map,
        title: "United States"
    });
    markers[2] = UnitedStatesMarker;

function dropdownChanged()
{
    var index = document.getElementById("myList3").value;
    var marker = markers[index];
    var position = marker.getPosition();
    map.setCenter(position);
}

The HTML:

<title>World Countries</title>
<style>
#map-canvas {
    top: 5px;
    left: 5px;
    width:75%;
    height:600px;
    border:1px solid black;
}    
#sidebar {
    width:325px;
    height:600px;
    position: absolute;
    top: 8px;
    right: 13px;
    text-align:center;
}    
</style>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="javascript4.js"></script>    
</head> 
<body>
<script>findYou();</script>
<div id="map-canvas"></div>
<div id="sidebar">
<h3>World Countries</h3>
<select id = "myList3" onchange="dropdownChanged();">
<option value = "">Select a Country</option>
<option value = "1">Your Location</option>
<option value = "2">United States</option>

If you're planning to manage a long list of markers, it's a bad idea to declare them right on your code. You'd be better off putting them in an array and looping over that array to encapsulate the desired behavior.

But first: you need two basic HTML elements here: a SELECT control to hold your destinations (we will say its ID is "selectlocation") and a DIV to hold the map.

<select id="selectlocation">
    <option value="10|10|3">Original Map</option>
</select>
<div id="map-canvas"></div>

The first option will reset the map to its original position and zoom. More on that later

Each element of your data array should contain the basics: the position of your marker (and eventual map center, when you have that location selected), the map zoom you want to see that location with and the location name. For example

var markerData= [
        {lat: 36.4 , lng: -120.9  , zoom: 7 , name: "California"},
        {lat: 28 , lng: -81  , zoom: 7 , name: "Florida"},
        {lat: 40.39 , lng: -3.67  , zoom: 8 , name: "Madrid"},
    ];

Then, when your map is already initialized, you can iterate over markerData to add both a marker and an option to the SELECT control.

markerData.forEach(function(data) {
    // Create a marker on given position
    var newmarker= new google.maps.Marker({
        map:map,
        position:{lat:data.lat, lng:data.lng},
        title: data.name
    });

    // Create an option on the SELECT control
    jQuery("#selectlocation").append('<option value="'+[data.lat, data.lng,data.zoom].join('|')+'">'+data.name+'</option>');
});

You see that each option has a value that means lat|lng|zoom, because I want the html element to hold all the info it needs to move and zoom the map.

Finally, I set a listener to the change event of the SELECT to move and zoom the map using the value of the selected option.

jQuery(document).on('change','#selectlocation',function() {
    var latlngzoom = jQuery(this).val().split('|');
    var newzoom = 1*latlngzoom[2],
    newlat = 1*latlngzoom[0],
    newlng = 1*latlngzoom[1];
    map.setZoom(newzoom);
    map.setCenter({lat:newlat, lng:newlng});
});

See the complete example working

There are several ways to do this, don't take mine as correct. You could have put the markers on an array and use the element to point to a given index in that array, or you could have used data attributes to avoid using split on the option value, but those are just implementation details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM