Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Build an Interactive Website Google Maps Integration Adding Point Markers to a Map

Chase Lester
Chase Lester
10,972 Points

Changing zoom for marker location?

I have one marker with my address and it is extremely zoomed in. How do I change the zoom level? Here is my code

$('#map_here').prepend('<div id="map"></div>');
        $(".static_map").remove();

        var map;
        var bounds;
        var geocoder;
        var center;

        function initialize() {
            var mapOptions = {
                center: new google.maps.LatLng(-34.397, 150.644),
                zoom: 5
            };
            map = new google.maps.Map(document.getElementById("map"),
            mapOptions);
            geocoder = new google.maps.Geocoder();
            bounds = new google.maps.LatLngBounds();
        }
        function addMarkerToMap(location){
            var marker = new google.maps.Marker({map: map, position: location});
            bounds.extend(location);
            map.fitBounds(bounds);
        }
        initialize();

        $("address").each(function(){
            var $address = $(this);
            geocoder.geocode({address: $address.text()}, function(results, status){
                if(status == google.maps.GeocoderStatus.OK) addMarkerToMap(results[0].geometry.location);
            });
        });

        google.maps.event.addDomListener(map, "idle", function(){
            center = map.getCenter();
        });

        $(window).resize(function(){
            map.setCenter(center);
        });

2 Answers

Chase Lester
Chase Lester
10,972 Points

Figured it out. Added this code before map.fitBounds(bounds) and it worked;

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
    if (this.getZoom() > 15) {
        this.setZoom(15);
   }
});
Chase Lester
Chase Lester
10,972 Points

Andrew Chalkley In your videos you do this for two markers. I have used the same code for one marker on my page I am building and it zooms in real close to that one marker. How would I fix this? Thanks!