简体   繁体   English

Google Maps API-自动居中和自动缩放

[英]Google Maps API - Auto Center and Auto Zoom

I am having trouble fitting auto center and auto Zoom on a map created from a CSV file that goes into a PHP array then transferred into JavaScript--code as follows - 我在从CSV文件创建的地图上拟合自动居中和自动缩放时遇到麻烦,该CSV文件进入PHP数组,然后转移到JavaScript中,代码如下-

<!DOCTYPE html>

<?php

include "getCsvData.php";   // this is where we put the data into a PHP array called $dataArray;
// now we exit the PHP and do the HTML including our Javascript...

?>

<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
    <link href="http://code.google.com/apis/maps/documentation/javascript/examples/standard.css" rel="stylesheet"
          type="text/css"/>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
        var geocoder;
        var map;
        var markers = [];
        var image = {
            url: 'src/icon' + 'a.png'
            ,
        };

        function initialize() {
            geocoder = new google.maps.Geocoder();
            var latlng = new google.maps.LatLng(0, 0);
            var myOptions = {
                zoom: 7,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            <?php
            for($i = 0, $j = count($postcodes); $i < $j - 1 ; $i++) {
            ?>
            addPostCode(<?php echo str_replace(array('[', ']'), '', json_encode($postcodes[$i])); ?>);
            <?php } ?>
        }
        function addPostCode(zip) {
            geocoder.geocode({'address': zip}, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {

                    map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: map,
                        icon: image,
                        position: results[0].geometry.location,
                        name: zip
                    });
                    markers.push(marker);
                    // latlng.extend(marker.position);
                } else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                    setTimeout(function () {
                        Geocode(address);
                    }, 200);
                }

                else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });

        }

    </script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="height:90%"></div>
</body>
</html>

I have found I need to use fitBounds but I cannot seem to get it working either the page doesn't load or it only center on one result and then I have to zoom out. 我发现我需要使用fitBounds但似乎无法正常工作,要么页面无法加载,要么页面仅以一个结果为中心,然后我必须缩小页面。

Here's for my setup for such case, Note that I use window here so I can access Google objects from any scope. 这是针对这种情况的设置,请注意,我在此处使用window ,因此我可以从任何范围访问Google对象。 You need to add each marker to mapBounds using extend() method and passing the position . 您需要使用extend()方法并传递position将每个标记添加到mapBounds

 $(function(){ window.gMap = new google.maps.Map(document.getElementById('map-canvas'), { zoom: 10, center: {lat: 37.769, lng: -122.446} }); var addresses = ["296 Gingerbread St", "383 Hoskins Ct", "1608 Liege Dr", "519 Mandalay Ct", "342 Pleasant Summit Dr", "1757 Quiver Point Ave", "174 Rising Mesa Ct", "26 Silica Sand St", "192 Thunder Plains Way", "277 Timber Hollow St", "367 Via Pacifico", "382 Washtenaw St"]; var timeOut = 0; $.each(addresses, function(i, address){ setTimeout(function(){ addMarker(address) }, timeOut); timeOut = timeOut+1600; }); }); function addMarker(address) { geoCoder.geocode({'address': address}, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { gMap.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: gMap, position: results[0].geometry.location, }); markers.push(marker); //extend the bounds to include each marker's position mapBounds.extend(marker.position); //now fit the map to the newly inclusive bounds gMap.fitBounds(mapBounds); } else { alert("Geocode was not successful for the following reason: " + status); } }); } 
 #map-canvas { width:80%; padding-left:15px; padding-right:15px; height:300px; border:2px solid #e8e8e8; border-radius:4px; margin:auto; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> function initMap() { window.mapBounds = new google.maps.LatLngBounds(); window.geoCoder = new google.maps.Geocoder(); window.markers = []; } </script> <script src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script> <div id="map-canvas"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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