code

Google 지도 API를 사용하여 마우스 스크롤 휠 스케일링을 비활성화하는 방법

starcafe 2023. 5. 18. 21:11
반응형

Google 지도 API를 사용하여 마우스 스크롤 휠 스케일링을 비활성화하는 방법

구글 맵 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에서 간단히 설정할 수 있습니다.scrollwheelMapOptions 속성 내에서 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확대/축소는 Maps 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 });
}

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

단순하게 하세요!오리지널 구글 지도 변수, 추가 사항 없음.

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

}

현재(2017년 10월) 구글은 확대/축소/스크롤을 처리하기 위한 특정 속성을 구현했습니다.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'
});

제스처 처리에 사용할 수 있는 값은 다음과 같습니다.

  • 'greedy'사용자가 화면을 끌 때 지도는 항상 상하좌우로 이동합니다.즉, 한 손가락 스와이프와 두 손가락 스와이프로 인해 지도가 이동합니다.
  • 'cooperative'사용자는 페이지를 스크롤하려면 손가락 하나로 문지르고 지도를 이동하려면 손가락 두 개를 사용해야 합니다.사용자가 한 손가락으로 지도를 스와이프하면 지도에 오버레이가 나타나고 두 손가락을 사용하여 지도를 이동하라는 메시지가 나타납니다.데스크톱 응용 프로그램에서 사용자는 수정자 키(ctrl 또는 ⌘ 키)를 누른 상태에서 스크롤하여 지도를 확대/축소하거나 이동할 수 있습니다.
  • 'none'이 옵션을 사용하면 모바일 장치의 지도 이동 및 고정, 데스크톱 장치의 지도 끌기를 사용할 수 없습니다.
  • 'auto'():(으)로가능한지 API 자바스크립트 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':false그 안에알림:저는 사용하고 있습니다. 아래는 제 CoffeeScript int 함수 제목입니다.

 $("#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 });
}

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

scrollwheel: false

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

지도를 한 번 클릭하면 확대/축소 스크롤이 활성화됩니다.그리고 마우스가 div를 종료한 후 비활성화합니다.

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

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>

간단한 솔루션:

// 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를 맵 뒤로 이동합니다.오버레이를 사용하면 한 번 클릭하면 확대/축소가 방지되고 지도 뒤에서는 확대/축소가 활성화됩니다.

어떻게 작동하는지에 대한 설명은 제 블로그 게시물 구글 지도에서 CSS로 확대/축소를 전환하고, 작업 데모는 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;
}

이 코드를 사용하면 구글 지도의 모든 색상과 확대/축소 제어를 할 수 있습니다.(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

반응형