Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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!