javascript GMaps - 当只有一个标记时,修复太多的自动放大

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript GMaps - 当只有一个标记时,修复太多的自动放大相关的知识,希望对你有一定的参考价值。

function initMao() {
  var options = {
    scrollwheel: false,
    mapTypeId: google.maps.MapTypeId.roadmap,
    styles: [],
    zoom: 14
  }
  
  var places = [
    {
      "address":"Lembah Desa",
      "latitude":"-7.8545142",
      "longitude":"110.3926986",
      "marker":""
    },{
      "address":"Glagah Futsal",
      "latitude":"-7.8543479",
      "longitude":"110.3876665",
      "marker":""
      
    }
  ];

  bounds = new google.maps.LatLngBounds();
  map = new google.maps.Map( document.getElementById( 'map' ), options);
  infoWindow = new google.maps.InfoWindow();

  map.setOptions({
    panControl: true,
    draggable: true,
    zoomControl: true,
    mapTypeControl: true,
    scaleControl: true,
  });

  var marker, i;

  map.setTilt(45);

  for ( i = 0; i < places.length; i++ ) {
    if ( places[i].latitude && places[i].longitude ) {
      position = new google.maps.LatLng( places[i].latitude, places[i].longitude );

      bounds.extend( position );

      marker = new google.maps.Marker({
        position: position,
        map: map,
        title: places[i].address,
        icon: ( places[i].marker ) ? places[i].marker : ''
      });

      google.maps.event.addListener( marker, 'click', ( function( marker, i ) {
        return function() { 
          if ( places[i].address && places[i].address.length > 1 ) {
            infoWindow.setContent( places[i].address );
            infoWindow.open( map, marker );
          } else {
            infoWindow.setContent( '' );
            infoWindow.close();
          }
        };
      })( marker, i ));

      /**
       * If there is only one marker, map.fitBounds will zoom-in too much.
       * Only run map.fitBounds if the markers are more than 1. Use setCenter
       * instead if the the marker is only 1.
       */
      if ( i > 0 ) {
        map.fitBounds( bounds );
      } else {
        map.setCenter( places[i].latitude, places[i].longitude );
        // Need to setZoom here as we didn't trigger bounds_changed event.
        map.setZoom( options.zoom );
      }
    }
  }

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

  var update = function() {
    google.maps.event.trigger( map, "resize" );
    map.setCenter( position );
  };
  update();

  var bindEvents = function() {
    $( window ).on( 'resize', update );
  };
  bindEvents();
};

以上是关于javascript GMaps - 当只有一个标记时,修复太多的自动放大的主要内容,如果未能解决你的问题,请参考以下文章

javascript Gmaps Icon(IE Friendly)

javascript Gmaps:SVG作为标记 - IE修复

Gmaps4rails - 当 JSON == "[]" 时,地图在第一次加载时抛出 JS 错误

GMaps API - 无响应

Gmaps API - 许多带有图标和标签的标记在移动设备上加载缓慢

gmaps.js 循环遍历地址并添加标记