jquery-gmap3

How to limit draggable area within a city using GMAP3 plugin?


I'm still new to google maps. And our instructor suggested GMAP3 plugin to use in our assignment. Yet, i only knew how to display it on my website.

I want to limit the draggable area in the specific city and limit the user in dragging outside the boundaries of that area, using GMAP3 plugin. Does anyone know to use this plugin?

I'm actually having a hard time now. Any help will be much appreciated.


Solution

  • First, you have to define the area (city, estate, country) unsing google.maps.LatLngBounds, for example EEUU:

    var strictBounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(28.70, -127.50), //bottom-left corner
        new google.maps.LatLng(48.85, -55.90) // top-right corner
    );
    

    In this case, I check the map center position with it is draged

    $('#your-map').gmap3({
        map:{
            options:{...},
            events:{
                dragend: function(map){
                    if (strictBounds.contains(map.getCenter())) return;
    
                    // We're out of bounds - Move the map back within the bounds
    
                    var c = map.getCenter(),
                        x = c.lng(),
                        y = c.lat(),
                        maxX = strictBounds.getNorthEast().lng(),
                        maxY = strictBounds.getNorthEast().lat(),
                        minX = strictBounds.getSouthWest().lng(),
                        minY = strictBounds.getSouthWest().lat();
    
                        if (x < minX) x = minX;
                        if (x > maxX) x = maxX;
                        if (y < minY) y = minY;
                        if (y > maxY) y = maxY;
    
                        map.setCenter(new google.maps.LatLng(y, x));
                }
            }
        }
    

    I hope to be helpful