0

I've wrote a code for my Rails app to show some locations on the google map using the following code:

var myOptions = {
        zoom: 2,
        center: new google.maps.LatLng(71.1333,27.7000, 13), // **I need to set the center from the locations in here.**
        mapTypeId: 'terrain'
    };
    map = new google.maps.Map($('#search_map_canvas')[0], myOptions);

    var addresses = <%=raw search_offering_addressess.to_json %>;
    for (var x = 0; x < addresses.length; x++) {
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
            var p = data.results[0].geometry.location
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            new google.maps.Marker({
                position: latlng,
                map: map
            });

        });
    }

Here, search_offering_addressess contains an array of locations. E.g. ["Berlin, germany", "zurich, switzerland", ....]

How can I find the midpoint of that locations? My map misses some locations marker.

Emu
  • 5,763
  • 3
  • 31
  • 51

1 Answers1

0

try this using LatLngBounds

      //newly added
        var bounds = new google.maps.LatLngBounds();
        var myOptions = {
                zoom: 2,
                center: new google.maps.LatLng(71.1333,27.7000, 13), // **I need to set the center from the locations in here.**
                mapTypeId: 'terrain'
            };


           map = new google.maps.Map($('#search_map_canvas')[0], myOptions);

            var addresses = <%=raw search_offering_addressess.to_json %>;
            for (var x = 0; x < addresses.length; x++) {
                $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
                    var p = data.results[0].geometry.location
                    var latlng = new google.maps.LatLng(p.lat, p.lng);
                    //newly added
                    bounds.extend(latlng);
                    new google.maps.Marker({
                        position: latlng,
                        map: map
                    });

                });
            }
  // Automatically center the map fitting all markers on the screen 
  map.fitBounds(bounds); 
Milind
  • 4,535
  • 2
  • 26
  • 58