Programing

Google Maps API로 마우스 스크롤 휠 크기 조정을 비활성화하는 방법

lottogame 2020. 10. 4. 10:17
반응형

Google Maps API로 마우스 스크롤 휠 크기 조정을 비활성화하는 방법


Google Maps API (v3)를 사용하여 페이지에 몇 개의지도를 그립니다. 제가하고 싶은 한 가지는지도 위에서 마우스 휠을 스크롤 할 때 확대 / 축소를 비활성화하는 것이지만 방법을 잘 모르겠습니다.

scaleControl을 비활성화 (즉, 크기 조정 UI 요소 제거)했지만 스크롤 휠 크기 조정을 방지하지는 않습니다.

다음은 내 기능의 일부입니다 (간단한 jQuery 플러그인).

$.fn.showMap = function(options, addr){
  options = $.extend({
    navigationControl: false,
    mapTypeControl: false,
    scaleControl: false,
    draggable: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }, options);
  var map = new google.maps.Map(document.getElementById($(this).attr('id')), options);

  // Code cut from this example as not relevant
};

Maps API 버전 3에서는 MapOptions 속성 scrollwheel내에서 간단히 옵션을 false로 설정할 수 있습니다.

options = $.extend({
    scrollwheel: false,
    navigationControl: false,
    mapTypeControl: false,
    scaleControl: false,
    draggable: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}, options);

Maps API 버전 2를 사용하는 경우 다음과 같이 disableScrollWheelZoom () API 호출 을 사용해야했습니다 .

map.disableScrollWheelZoom();

scrollwheel줌은지도 API 버전 3에서 기본적으로 사용하지만, 명시 적으로 활성화하지 않는 한 버전 2에서 사용할 수 없습니다되는 enableScrollWheelZoom()API 호출.


Daniel의 코드 가 작업을 수행합니다 (힙 감사합니다!). 하지만 확대 / 축소를 완전히 비활성화하고 싶었습니다. 이렇게하려면 다음 네 가지 옵션을 모두 사용해야합니다.

{
  zoom: 14,                        // Set the zoom level manually
  zoomControl: false,
  scaleControl: false,
  scrollwheel: false,
  disableDoubleClickZoom: true,
  ...
}

참조 : MapOptions 객체 사양


이 작업을 동적으로 수행하려는 경우에만;

function enableScrollwheel(map) {
    if(map) map.setOptions({ scrollwheel: true });
}

function disableScrollwheel(map) {
    if(map) map.setOptions({ scrollwheel: false });
}

때로는지도 위에 "복잡한"무언가를 표시해야합니다 (또는지도가 레이아웃의 작은 부분 임).이 스크롤 확대 / 축소는 중간에 있지만 일단 깨끗한지도가 있으면이 확대 / 축소 방법이 좋습니다.


간단하게! 원본 Google지도 변수, 추가 항목 없음.

 var mapOptions = {
     zoom: 16,
     center: myLatlng,
     scrollwheel: false

}

현재 (2017 년 10 월) Google은 확대 / 축소 / 스크롤을 처리하는 gestureHandling. 그 목적은 모바일 장치 작동을 처리하는 것이지만 데스크톱 브라우저의 동작도 수정합니다. 공식 문서 에서 가져온 것입니다 .

function initMap() {
  var locationRio = {lat: -22.915, lng: -43.197};
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: locationRio,
    gestureHandling: 'none'
});

gestureHandling에 사용할 수있는 값은 다음과 같습니다.

  • 'greedy': 사용자가 화면을 스 와이프 (드래그)하면지도가 항상 이동 (위 또는 아래, 왼쪽 또는 오른쪽)됩니다. 즉, 한 손가락으로 스 와이프하고 두 손가락으로 스 와이프하면지도가 이동합니다.
  • 'cooperative': 페이지를 스크롤하려면 한 손가락으로 스 와이프하고지도를 이동하려면 두 손가락으로 스 와이프해야합니다. 사용자가 한 손가락으로지도를 스 와이프하면지도를 이동할 때 두 손가락을 사용하라는 메시지와 함께 오버레이가지도에 표시됩니다. 데스크톱 애플리케이션에서 사용자는 수정 자 키 (ctrl 또는 ⌘ 키)를 누른 상태에서 스크롤하여지도를 확대 / 축소하거나 이동할 수 있습니다.
  • 'none':이 옵션은 모바일 장치의 경우지도에서 이동 및 집기, 데스크톱 장치에서지도의 끌기를 비활성화합니다.
  • 'auto'(기본값) : 페이지를 스크롤 할 수 있는지 여부에 따라 Google Maps JavaScript API는 gestureHandling 속성을 'cooperative'또는'greedy'

간단히 말해 "항상 확대 / 축소 가능 "( 'greedy'), "확대 가능 안 함"( 'none') 또는 "확대 / 축소를 활성화하려면 사용자가 CRTL / ⌘를 눌러야 함 "( )으로 쉽게 설정할 수 있습니다 'cooperative'.


멋진 버튼으로지도를 잠 그거나 잠금 해제 할 수있는 좀 더 개발 된 jQuery 플러그인을 만들었습니다.

이 플러그인은 투명한 오버레이 div가있는 Google지도 iframe을 비활성화하고 잠금 해제 버튼을 추가합니다. 잠금을 해제하려면 650 밀리 초 동안 눌러야합니다.

편의를 위해 모든 옵션을 변경할 수 있습니다. https://github.com/diazemiliano/googlemaps-scrollprevent 에서 확인 하세요.

여기에 몇 가지 예가 있습니다.

(function() {
  $(function() {
    $("#btn-start").click(function() {
      $("iframe[src*='google.com/maps']").scrollprevent({
        printLog: true
      }).start();
      return $("#btn-stop").click(function() {
        return $("iframe[src*='google.com/maps']").scrollprevent().stop();
      });
    });
    return $("#btn-start").trigger("click");
  });
}).call(this);
.embed-container {
  position: relative !important;
  padding-bottom: 56.25% !important;
  height: 0 !important;
  overflow: hidden !important;
  max-width: 100% !important;
}
.embed-container iframe {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
}
.mapscroll-wrap {
  position: static !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/diazemiliano/googlemaps-scrollprevent/v.0.6.5/dist/googlemaps-scrollprevent.min.js"></script>
<div class="embed-container">
  <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d12087.746318586604!2d-71.64614110000001!3d-40.76341959999999!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x9610bf42e48faa93%3A0x205ebc786470b636!2sVilla+la+Angostura%2C+Neuqu%C3%A9n!5e0!3m2!1ses-419!2sar!4v1425058155802"
  width="400" height="300" frameborder="0" style="border:0"></iframe>
</div>
<p><a id="btn-start" href="#">"Start Scroll Prevent"</a>  <a id="btn-stop" href="#">"Stop Scroll Prevent"</a>
</p>


제 경우 중요한 것은 'scrollwheel':falseinit 에 설정하는 것이 었습니다 . 고시 : 나는 jQuery UI Map. 아래는 내 CoffeeScript init 함수 제목입니다.

 $("#map_canvas").gmap({'scrollwheel':false}).bind "init", (evt, map) ->

지오 코딩 및 사용자 지정 핀과 같은 작업을 좀 더 쉽게 수행 할 수있는 GMaps.js 라이브러리를 사용하는 경우를 대비 하여 이전 답변에서 배운 기술을 사용하여이 문제를 해결하는 방법은 다음과 같습니다.

var Gmap = new GMaps({
  div: '#main-map', // FYI, this setting property used to be 'el'. It didn't need the '#' in older versions
  lat: 51.044308,
  lng: -114.0630914,
  zoom: 15
});

// To access the Native Google Maps object use the .map property
if(Gmap.map) {
  // Disabling mouse wheel scroll zooming
  Gmap.map.setOptions({ scrollwheel: false });
}

Javascript Google Map API 를 비활성화하는 방법을 궁금해하는 사람을 위해

지도를 한 번 클릭하면 확대 스크롤 활성화 됩니다. 그리고 비활성화 마우스 후 사업부를 종료합니다.

다음은 몇 가지 예입니다.

var map;
var element = document.getElementById('map-canvas');
function initMaps() {
  map = new google.maps.Map(element , {
    zoom: 17,
    scrollwheel: false,
    center: {
      lat: parseFloat(-33.915916),
      lng: parseFloat(151.147159)
    },
  });
}


//START IMPORTANT part
//disable scrolling on a map (smoother UX)
jQuery('.map-container').on("mouseleave", function(){
  map.setOptions({ scrollwheel: false });
});
jQuery('.map-container').on("mousedown", function() {
  map.setOptions({ scrollwheel: true });
});
//END IMPORTANT part
.big-placeholder {
  background-color: #1da261;
  height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <body>
      <div class="big-placeholder">
      </div>
      
      
      <!-- START IMPORTANT part -->
      <div class="map-container">
        <div id="map-canvas" style="min-height: 400px;"></div>  
      </div>
      <!-- END IMPORTANT part-->
      
      
      
      <div class="big-placeholder">
      </div>
      <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAIjN23OujC_NdFfvX4_AuoGBbkx7aHMf0&callback=initMaps">
      </script>
  </body>
</html>


지도 옵션을 추가하기 만하면됩니다.

scrollwheel: false

간단한 해결책 :

// DISABLE MOUSE SCROLL IN MAPS
// enable the pointer events only on click;
$('.gmap-wrapper').on('click', function () {
  $('.gmap-wrapper iframe').removeClass('scrolloff'); // set the pointer events true on click
});
// you want to disable pointer events when the mouse leave the canvas area;
$(".gmap-wrapper").mouseleave(function () {
  $('.gmap-wrapper iframe').addClass('scrolloff'); // set the pointer events to none when mouse leaves the map area
});
.scrolloff{ pointer-events: none; }
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="gmap-wrapper">
<iframe class="scrolloff" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d44754.55736493158!2d9.151166379101554!3d45.486726!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4786bfca7e8fb1cb%3A0xee8d99c9d153be98!2sCorsidia!5e0!3m2!1sit!2sit!4v1496947992608" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
</html>

출처 : https://github.com/Corsidia/scrolloff


누군가가 이것에 대한 순수한 CSS 솔루션에 관심이있는 경우를 대비하십시오. 다음 코드는지도 ​​위에 투명 div를 오버레이하고 클릭하면 투명 div를지도 뒤로 이동합니다. 오버레이는 확대 / 축소를 방지하고 클릭하면 확대 / 축소가 활성화됩니다.

작동 방식에 대한 설명 은 내 블로그 게시물 Google Maps toggle zoom with css , pen codepen.io/daveybrown/pen/yVryMr 을 참조하세요.

면책 조항 : 이것은 주로 학습용이며 프로덕션 웹 사이트를위한 최상의 솔루션이 아닐 수 있습니다.

HTML :

<div class="map-wrap small-11 medium-8 small-centered columns">
    <input id="map-input" type="checkbox" />
    <label class="map-overlay" for="map-input" class="label" onclick=""></label>
    <iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d19867.208601651986!2d-0.17101002911118332!3d51.50585742500925!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2suk!4v1482355389969"></iframe>
</div>

CSS :

.map-wrap {
    position: relative;
    overflow: hidden;
    height: 180px;
    margin-bottom: 10px;
}

#map-input {
    opacity: 0;
}

.map-overlay {
    display: block;
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100% !important;
    height: 100% !important;
    overflow: hidden;
    z-index: 2;    
}

#map-input[type=checkbox]:checked ~ iframe {
    z-index: 3;
}

#map-input[type=checkbox]:checked ~ .map-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100% !important;
    height: 100% !important;
}


iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100% !important;
    height: 100% !important;
    z-index: 1;
    border: none;
}

해당 코드를 사용하면 Google지도의 모든 색상 및 확대 / 축소 제어가 제공됩니다. ( scaleControl : falsescrollwheel : false 는 마우스 휠이 확대 또는 축소되지 않도록합니다.)

function initMap() {
            // Styles a map in night mode.
            var map = new google.maps.Map(document.getElementById('map'), {
                center: {lat: 23.684994, lng: 90.356331},
                zoom: 8,
                scaleControl: false,
                scrollwheel: false,
              styles: [
                {elementType: 'geometry', stylers: [{color: 'F1F2EC'}]},
                {elementType: 'labels.text.stroke', stylers: [{color: '877F74'}]},
                {elementType: 'labels.text.fill', stylers: [{color: '877F74'}]},
                {
                  featureType: 'administrative.locality',
                  elementType: 'labels.text.fill',
                  stylers: [{color: '#d59563'}]
                },
                {
                  featureType: 'poi',
                  elementType: 'labels.text.fill',
                  stylers: [{color: '#d59563'}]
                },
                {
                  featureType: 'poi.park',
                  elementType: 'geometry',
                  stylers: [{color: '#263c3f'}]
                },
                {
                  featureType: 'poi.park',
                  elementType: 'labels.text.fill',
                  stylers: [{color: '#f77c2b'}]
                },
                {
                  featureType: 'road',
                  elementType: 'geometry',
                  stylers: [{color: 'F5DAA6'}]
                },
                {
                  featureType: 'road',
                  elementType: 'geometry.stroke',
                  stylers: [{color: '#212a37'}]
                },
                {
                  featureType: 'road',
                  elementType: 'labels.text.fill',
                  stylers: [{color: '#f77c2b'}]
                },
                {
                  featureType: 'road.highway',
                  elementType: 'geometry',
                  stylers: [{color: '#746855'}]
                },
                {
                  featureType: 'road.highway',
                  elementType: 'geometry.stroke',
                  stylers: [{color: 'F5DAA6'}]
                },
                {
                  featureType: 'road.highway',
                  elementType: 'labels.text.fill',
                  stylers: [{color: 'F5DAA6'}]
                },
                {
                  featureType: 'transit',
                  elementType: 'geometry',
                  stylers: [{color: '#2f3948'}]
                },
                {
                  featureType: 'transit.station',
                  elementType: 'labels.text.fill',
                  stylers: [{color: '#f77c2b3'}]
                },
                {
                  featureType: 'water',
                  elementType: 'geometry',
                  stylers: [{color: '#0676b6'}]
                },
                {
                  featureType: 'water',
                  elementType: 'labels.text.fill',
                  stylers: [{color: '#515c6d'}]
                },
                {
                  featureType: 'water',
                  elementType: 'labels.text.stroke',
                  stylers: [{color: '#17263c'}]
                }
              ]
            });
    
             var marker = new google.maps.Marker({
              position: {lat: 23.684994, lng: 90.356331},
              map: map,
              title: 'BANGLADESH'
            });
          }


이 간단한 시험으로 수행합니다.

jQuery

$('.map').click(function(){
    $(this).find('iframe').addClass('clicked')
    }).mouseleave(function(){
    $(this).find('iframe').removeClass('clicked')
});

CSS

.map {
    width: 100%; 
}
.map iframe {
    width: 100%;
    display: block;
    pointer-events: none;
    position: relative; /* IE needs a position other than static */
}
.map iframe.clicked {
    pointer-events: auto;
}

또는 gmap 옵션을 사용하십시오.

function init() { 
    var mapOptions = {  
        scrollwheel: false, 

참고 URL : https://stackoverflow.com/questions/2330197/how-to-disable-mouse-scroll-wheel-scaling-with-google-maps-api

반응형