dongpo1846 2016-08-02 06:43
浏览 29
已采纳

如何使用多个地图指针制作Google地图以在打开页面时缩放特定区域/位置

I'm not able to zoom to a particular area/location in Google maps which has multiple Map Pointers. At present it automatically centers the map covering all locations. But what I need is to zoom to a particular location upon opening the webpage. Here is my code,

<script>
jQuery(function ($) {
    // Asynchronously Load the map API 
    var script = document.createElement('script');
    script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyA157quXbUlHHgm4wJJxzD49MivKgPSil8&sensor=false&callback=initialize";
    document.body.appendChild(script);
});

function initialize() {
    locations = <?php echo json_encode($sl_select_obj) ?>;
    markerdata = JSON.parse('<?php echo json_encode($locations_data) ?>');


    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap',
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);

    // Multiple Markers''
    // $info='';
    var markers = locations;

    <?php
    $total = count($locations_data);
    $markerinfo = '';
    $c = 0;
    foreach ($locations_data as $key => $info):
        if ($c != $total):
            $markerinfo .="['<div class=\"info_content\"><h2>" . $info['loctitle'] . "</h2><h3><a href=" . $info['site'] . ">" . $info['site'] . "</a></h3><h3><a href=" . $info['locpermalink'] . ">View Full Office Details</a></h3></div>'],";
        else:
            $markerinfo .="['<div class=\"info_content\"><h2>" . $info['loctitle'] . "</h2><h3><a href=" . $info['site'] . ">" . $info['site'] . "</a></h3><h3><a href=" . $info['locpermalink'] . ">View Full Office Details</a></h3></div>']";
        endif;
        $c++;
    endforeach;
    ?>



    // Info Window Content                        
    var infoWindowContent = [<?php echo $markerinfo; ?>]; //markerdata; 



    // Display multiple markers on a map
    var infoWindow = new google.maps.InfoWindow(), marker, i;

    // Loop through our array of markers & place each one on the map  
    for (i = 0; i < markers.length; i++) {
        var position = new google.maps.LatLng(markers[i]["lat"], markers[i]["long"]);
        bounds.extend(position);
        marker = new google.maps.Marker({
            position: position,
            map: map,
            title: markers[i]["address"],
            icon: '<?php bloginfo('template_directory'); ?>/images/venue-direct-icon.png'
        });

        // Allow each marker to have an info window    
        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infoWindow.setContent(infoWindowContent[i][0]);
                infoWindow.open(map, marker);
            }
        })(marker, i));

        // Automatically center the map fitting all markers on the screen
        map.fitBounds(bounds);
    }

    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {
        this.setZoom(7);
        google.maps.event.removeListener(boundsListener);
    });
    map.fitBounds(markerBounds);

}

  • 写回答

2条回答 默认 最新

  • donglei2022 2016-08-02 06:51
    关注

    Try to add the "center" option like this:

    var mapOptions = {
        center: new google.maps.LatLng(51.5287718, -0.2416803),
        mapTypeId: 'roadmap',
        zoom: 15,
        draggable: map_draggable,
        scrollwheel: map_scrollwheel
    };
    

    EDIT: To help you this is a code similar that I use in my project: multiple positions, center on the first if only one, else I use google autocenter for all positions.

    jQuery( document ).ready( function( $ ) {
    
    if($(window).width()>991){
        var map_draggable = true;
        var map_scrollwheel = false;
    } else {
        var map_draggable = false;
        var map_scrollwheel = false;
    }
    
    var offices = [];
    $('#map-google-container')
        .find('.hidden')
        .each(function(){
            offices[offices.length] = 
            {
                "latitude":$(this).attr('latitude'),
                "longitude":$(this).attr('longitude'),
                "content":$(this).attr('content')
            };
        });
    var mapOptions = {
        zoom: 6,
        center: new google.maps.LatLng(offices[0].latitude, offices[0].longitude),
        draggable: map_draggable,
        scrollwheel: map_scrollwheel,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        panControl: true
    };
    var map = new google.maps.Map(document.getElementById('map-google'), mapOptions);
    var map_styles = [
      {
        featureType: "all",
        stylers: [
            { hue: "#F69200" }, 
            { saturation: -50 }
        ]
      },{ 
        featureType: "water", 
        stylers: [ 
            { color: "#efefef" } 
        ] 
      } 
    ];
    map.setOptions({styles: map_styles});
    var image = '/include/images/marker.png';
    
    var bounds = new google.maps.LatLngBounds();
    
    for (i = 0; i < offices.length; i++)
    {  
        var content = offices[i].content;
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(offices[i].latitude, offices[i].longitude),
            map: map,
            icon: image,
            animation: google.maps.Animation.DROP,
            title: content
        });
    
        bounds.extend(marker.position);
    
        var infowindow = new google.maps.InfoWindow();
    
        google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
            return function() {
               infowindow.setContent(content);
               infowindow.open(map,marker);
            };
        })(marker,content,infowindow));
    }
    
    if (offices.length > 1) { map.fitBounds(bounds); }
    });
    

    In my project I have to list all the offices and show a unique map with all of them. So in the HTML I put the information of all offices (hidden for the user). In JavaScript I loop through these properties and populate the map.

    Hope it helps

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法