谷歌地图V3地图集中心不使用多个标记

时间:2016-06-08 14:05:24

标签: javascript google-maps

您好我无法设置Google地图的中心 我正在使用谷歌地图与以下代码。我有多个标记,我想设置一个标记在中心不允许,另一个在特定位置。

             function displayMarkers()

             {

           var bounds = new google.maps.LatLngBounds();



        var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
        var address1 = markersData[i].address1;
        var address2 = markersData[i].address2;
        var address3 = markersData[i].address3;
        var address4 = markersData[i].address4;
        var postalCode = markersData[i].postalCode;
        var colormap = markersData[i].colormap;
        var isMain = markersData[i].isMain;
        var urls=markersData[i].url;

        createMarker(latlng, address1, address2,address3,address4,postalCode,colormap,isMain,urls );

        // Marker’s Lat. and Lng. values are added to bounds variable
         bounds.extend(latlng);

     }
     // Finally the bounds variable is used to set the map bounds
     // with API’s fitBounds() function
     map.fitBounds(bounds);

}

function createMarker(latlng, address1, address2, address3,address4,postalCode,colormap,isMain,urls)
{
if(isMain==false)
{
    var pinColor = colormap;
    var pinsImage ="https://maps.google.com/mapfiles/ms/icons/"+pinColor;

    var marker = new google.maps.Marker({
                 map: map,
                 position: latlng,
                 title: name,
                 icon: pinsImage,
                 //shadow: pinShadow
                  url: urls
    });



    // This event expects a click on a marker
    // When this event is fired the infowindow content is created
    // and the infowindow is opened
    google.maps.event.addListener(marker, 'click', function() {

    // Variable to define the HTML content to be inserted in the infowindow
    var iwContent = '<div id="iw_container">' +
    '<div class="iw_title">' + name + '</div>' +
    '<div class="iw_content">' + address1 + '<br />' +
    address2 + '<br />' +
    postalCode + '</div></div>';

     window.open(marker.url);

    // including content to the infowindow
    //infoWindow.setContent(iwContent);

    // opening the infowindow in the current map and at the current marker location
    //infoWindow.open(map, marker);
    });
    }
   map.setCenter(new google.maps.LatLng(mainlag, mainlng));
 }
 function initialize() 
 {
    intialPointer();
    var pinColor = maincolormap;
    var pinsImage ="https://maps.google.com/mapfiles/ms/icons/"+pinColor;

    var myLatlng = new google.maps.LatLng(mainlag,mainlng);
    alert(myLatlng );
    var mapOptions = {center: myLatlng,
                      zoom: 5,
                      //icon: pinsImage,
                      mapTypeId: google.maps.MapTypeId.ROADMAP,
                      };
    var markers = new google.maps.Marker({
                     position: myLatlng,
                     icon: pinsImage,

     });

    map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);

    markers.setMap(map);

    var mapBoundary = new google.maps.LatLngBounds();
    mapBoundary.extend(myLatlng );
    map.fitBounds(mapBoundary);
    map.setCenter(map); 



    // Variable to define the HTML content to be inserted in the infowindow
    var iwContent = '<div id="con">' +
    '<div class="ti">' + accname + '</div>' +
    '<div class="tent">' + mainaddress1+ '<br />' +
    mainaddress2+ '<br />' +
    mainpostalcode+ '</div></div>';

    var infowindow = new google.maps.InfoWindow({
        content: iwContent 
    });


    // Event that opens the InfoWindow with a click on the map
    google.maps.event.addListener(markers, 'click', function() {
        infowindow.open(map, markers); 
    });

    // Event that closes the InfoWindow with a click on the map
    google.maps.event.addListener(map, 'click', function() { infoWindow.close();

    });

    // Finally displayMarkers() function is called to begin the markers creation
    displayMarkers();
}

google.maps.event.addDomListener(window, 'load', initialize);

1 个答案:

答案 0 :(得分:0)

根据Google Maps JavaScript Reference,您没有正确使用.setCenter()方法 看一看:

  

setCenter(经纬度:经纬度| LatLngLiteral)

这意味着,您必须使用的参数是地图中心所需标记的LatLng,如下所示:

var chicago = {lat: 41.85, lng: -87.65};
map.setCenter(chicago);

或使用标记,您可以这样做:

map.setCenter(marker.getPosition());

(编辑)一个更完整的例子:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Street View side-by-side</title>
    <style>
        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        
        #map {
            float: left;
            height: 100%;
            width: 100%;
        }
        
        .controls {
            margin-top: 10px;
            border: 1px solid transparent;
            border-radius: 2px 0 0 2px;
            box-sizing: border-box;
            -moz-box-sizing: border-box;
            height: 32px;
            outline: none;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        }
        
        #pac-input {
            background-color: #fff;
            font-family: Roboto;
            font-size: 15px;
            font-weight: 300;
            margin-left: 12px;
            padding: 0 11px 0 13px;
            text-overflow: ellipsis;
            width: 300px;
        }
        
        #pac-input:focus {
            border-color: #4d90fe;
        }
        
        .pac-container {
            font-family: Roboto;
        }
    </style>
</head>

<body>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map"></div>

    <script>
        //setting variables to be accessible outside the initialize function
        var map;
        var markers = [];
        var searchBox;
        var bounds;

        function initialize() {
            //Setting the tower Agbar of Barcelona as my starting point
            var agbar = new google.maps.LatLng(41.4035482, 2.1894355);
            map = new google.maps.Map(document.getElementById('map'), {
                center: agbar,
                zoom: 14
            });



            //SEARCH BOX

            // Create the search box and link it to the UI element.
            var input = document.getElementById('pac-input');
            var searchBox = new google.maps.places.SearchBox(input);
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

            // Bias the SearchBox results towards current map's viewport.
            map.addListener('bounds_changed', function() {
                searchBox.setBounds(map.getBounds());
            });


            // Listen for the event fired when the user selects a prediction and retrieve
            // more details for that place.
            searchBox.addListener('places_changed', function() {
                var places = searchBox.getPlaces();

                if (places.length == 0) {
                    return;
                }

                // Clear out the old markers.
                markers.forEach(function(marker) {
                    marker.setMap(null);
                });
                markers = [];

                // For each place, get the icon, name and location.
                bounds = new google.maps.LatLngBounds();
                places.forEach(function(place, index) {
                    //set the icon for each place
                    var icon = {
                        url: place.icon,
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(25, 25)
                    };
                    // Create a marker for each place.
                    var marker = new google.maps.Marker({
                        map: map,
                        icon: icon,
                        title: 'Result #' + (index + 1) + ' ' + place.formatted_address,
                        position: place.geometry.location
                    });
                    //extend bounds to all places 
                    bounds.extend(place.geometry.location);
                });
                //Now set center of map in, let's say, first result:
                map.setCenter(places[0].geometry.location)
                    //and you could also set a close zoom
                //map.setZoom(16);
            });
        }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&callback=initialize">
    </script>
</body>

</html>

使用此代码段并查看结果的说明:

  1. 在searchBox内搜索关键字“bars”,它将返回10个结果。
  2. 使用右下角的“+控件”进行缩放,直到您看到结果#1确实位于地图的中心:)
  3. 注意:将鼠标悬停在标记上时,您会看到地点的编号和地址