如何在装配后居中谷歌地图

时间:2018-04-12 10:24:48

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

我需要一些Google地图的帮助。 在装配后我无法降低谷歌地图中的缩放级别。 问题是我得到了一个非常高度缩放的谷歌地图。我已经尝试将缩放级别设置为5(正如您在代码中看到的那样),但这对高度缩放的地图没有影响。 我想实现这个enter image description here

但是现在它的到来是这样的: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);
    });
  });
});

我尝试了许多选项,但没有一个可行。请帮忙。

1 个答案:

答案 0 :(得分:0)

我可以看到,问题在于Google Maps sdk。为什么?因为他们在bounds_changed实际结束之前呼叫fitBounds回调 这就是为什么它导致缩放不起作用的原因,因为他们没有完成缩放,因为fitBounds中的边界变化。

因此解决方案是将setZoom放入setTimeout。这样,此代码将仅在执行当前进程后运行 - fitBounds

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

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