【问题标题】:How to centre the google map after fitboundfitbounds后如何使谷歌地图居中
【发布时间】:2023-03-26 09:46:01
【问题描述】:

我需要一些有关 Google 地图的帮助。 fitbound 后我无法降低谷歌地图的缩放级别。 问题是我得到了一个高度放大的谷歌地图。我尝试将缩放级别设置为 5(如您在代码中所见),但这对高度缩放的地图没有影响。 我想实现这个

但现在它的到来是这样的:http://redstoneinfotech.com/OSAcontact/

这里是 map.js

window.map = {
  map_type: 'ROADMAP',
  map_zoom: 5,
  map_style: 'blackwhite',
  map_scrollable: 'on',
  marker: 'show',
  label: ['Castle Hill', 'Sydney', 'Melbourne', 'Milton', 'Brooklyn Park', 'Wangara '],
  address: '',
  latlng: ['-33.7301484, 150.9626532', '-33.8473567, 150.6517813',
    '-37.970154, 144.4926753 ', ' - 27.4691402, 152.9962768 ',
    ' - 34.9303517, 138.5346949 ', ' - 31.7928896, 115.8157212 '
  ],
  center_latlng: '',
  markerURL: 'assets/images/marker.png',
  auto_center: true,
};

'use strict';

jQuery(document).ready(function($) {

  $('.google-map').each(function() {
    var mapDiv = $(this);
    var mapData = window[mapDiv.attr('id')];

    function createMap() {
      var style = [{
        'stylers': [{
          'saturation': -100
        }]
      }];

      var options = {
        zoom: parseInt(mapData.map_zoom, 5),
        scrollwheel: false,
        draggable: mapData.map_scrollable === 'on',
        mapTypeId: google.maps.MapTypeId[mapData.map_type]
      };

      if (mapData.map_style === 'blackwhite') {
        options.styles = style;
      }

      return new google.maps.Map(mapDiv[0], options);
    }

    // create map
    var map = createMap();

    // create bounds in case we dont have center map coordinates
    // every time a marker is added we increase the bounds
    var bounds = new google.maps.LatLngBounds();

    function addMarker(position, index) {
      if (mapData.marker === 'show') {
        var image = {
          url: mapData.markerURL,
          size: new google.maps.Size(30, 48),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(10, 40)
        };

        var marker = new google.maps.Marker({
          position: position,
          icon: image,
          map: map
        });

        // extend bounds to encase new marker
        bounds.extend(position);

        // add label popup to marker
        if (mapData.label[index] !== undefined) {
          var infoWindow = new google.maps.InfoWindow({
            content: mapData.label[index]
          });
          google.maps.event.addListener(marker, 'click', function(e) {
            infoWindow.open(map, this);
          });
        }

      }
    }

    // centre map

    var centerMapWithCoordinates = !mapData.auto_center;
    if (centerMapWithCoordinates) {
      if (mapData.center_latlng !== undefined) {
        var center_lat_lng = mapData.center_latlng.split(',');
        var center_map = new google.maps.LatLng(center_lat_lng[0], center_lat_lng[1]);
        map.setCenter(center_map);
      } else {
        console.log('You have not set any coordinates for the map to be centered at.');
      }
    }

    // create markers
    if (mapData.address) {
      // lookup addresses
      var markerAddressCount = 0;
      $.each(mapData.address, function(index, address) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
          'address': address
        }, function(results, status) {
          if (status === google.maps.GeocoderStatus.OK) {
            if (undefined !== results[0]) {
              var location = results[0].geometry.location;
              var position = new google.maps.LatLng(location.lat(), location.lng());
              addMarker(position, index);
            }

            // increment count so we can keep track of all markers loaded
            markerAddressCount++;
            // if all markers are loaded then fit map
            if (!centerMapWithCoordinates && markerAddressCount === mapData.address.length) {
              map.fitBounds(bounds);
            }
          } else {
            console.log('Geocode was not successful for the following reason: ' + status);
          }
        });
      });
    } else if (undefined !== mapData.latlng) {
      for (var i = 0; i < mapData.latlng.length; i++) {
        var coordinates = mapData.latlng[i].split(',');
        var position = new google.maps.LatLng(coordinates[0], coordinates[1]);
        addMarker(position, i);
      }
      if (!centerMapWithCoordinates) {
        map.fitBounds(bounds);
      }
    }

    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
      this.setZoom(5);
      google.maps.event.removeListener(boundsListener);
    });
  });
});

我尝试了很多选项,但没有一个有效。请帮忙。

【问题讨论】:

  • 只有在 fitBounds 被调用后才添加监听器...
  • @AKX 我应该从 var =boundListener 中删除代码吗?
  • @MoshFeu 什么都没试过。
  • 您可以为此创建一个工作 snippet 吗?我这样帮你会容易得多。
  • @MoshFeu 我可以给你发电子邮件吗?如果是,请分享您的电子邮件

标签: javascript google-maps google-maps-api-3


【解决方案1】:

据我所知,问题出在 Google Maps sdk 上。为什么?因为他们在 fitBounds 实际结束之前调用了 bounds_changed 回调。
这就是为什么它会导致缩放不起作用,因为他们没有完成缩放它作为fitBounds 中边界变化的一部分。

所以解决方案是将setZoom 放入setTimeout。这样,这段代码只会在当前进程执行后才会运行——fitBounds

setTimeout(() => {
  this.setZoom(5);
}, 0);

它对我有用。让我知道它是否适合你。

【讨论】:

    猜你喜欢
    • 2016-06-16
    • 2017-10-09
    • 2012-01-15
    • 1970-01-01
    • 2017-03-23
    • 2012-11-26
    • 2012-05-03
    • 2011-12-31
    • 2012-07-23
    相关资源
    最近更新 更多