Embed Google Maps on page without overriding iPhone scroll behavior

可紊 提交于 2019-11-27 19:11:45

I solved it by upgrading to v3 and then detecting a basic javascript error in my use of the code from the solution linked above. The key was

start = (events == "touch") ? e.touches[0].pageY : e.clientY; 

The user must have been setting the events variable somewhere outside the presented code, since it looks like the matching assignment is for touch events and the else assignment is for key events. But since I didn't have an events variable it was defaulting to the wrong assignment. I simply changed mine to start = e.touches[0].pageY (and did the same for the touchend event) and now everything works.

However, I switched back to v2 to see if it would work with that javascript error corrected, and it did not. So it looks like I did not waste any time upgrading to v3, neither in figuring out this specific solution nor in setting myself up for future compatibility.

In conclusion, if you want to embed Google Maps on a mobile page and be able to scroll past it, you need to use API v3, disable dragging, and add touch events. I made a few minor tweaks to my code as well, presented here for any who may benefit in the future:

function initialize() 
{
    geocoder = new google.maps.Geocoder();
    var myOptions = {
       mapTypeId: google.maps.MapTypeId.ROADMAP             
    };

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function showAddress(address, zoom) 
{
   if (geocoder) 
   {
      geocoder.geocode( { 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            map.setOptions( { zoom: zoom });
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
         }
      });
   }
}

initialize(); 
showAddress("'.$geocode_address.'");

map.setOptions( { draggable: false });

var dragFlag = false;
var start = 0, end = 0;

function thisTouchStart(e)
{
    dragFlag = true;
    start = e.touches[0].pageY; 
}

function thisTouchEnd()
{
    dragFlag = false;
}

function thisTouchMove(e)
{
    if ( !dragFlag ) return;
    end = e.touches[0].pageY;
    window.scrollBy( 0,( start - end ) );
}

document.getElementById("map_canvas").addEventListener("touchstart", thisTouchStart, true);
document.getElementById("map_canvas").addEventListener("touchend", thisTouchEnd, true);
document.getElementById("map_canvas").addEventListener("touchmove", thisTouchMove, true);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!