Tomas Bajoras
Tomas Bajoras

Reputation: 349

How to make google map NOT centered, but a little bit above?

I have created function, which is centering me google map, but I need to make it a little bit above, because me description window is not visible.

This is picture how it looks:

enter image description here

And this is picture how I want to look:

enter image description here

Here is a js script.

   var address = "{{$restaurant->address}}";
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {

     var latlng = new google.maps.LatLng(-34.397, 150.644);
     var mapOptions = {
       zoom: 17,
       scrollwheel: false,
       styles: styleArray,
       center: latlng
     }
     map = new google.maps.Map(document.getElementById("map"), mapOptions);

     map.setCenter(results[0].geometry.location);
     marker = new google.maps.Marker({
        map: map,
        animation: google.maps.Animation.DROP,
        position: results[0].geometry.location
    });

     var contentString = "<b style='color:black'>{{$restaurant->address}}</b>"; // HTML text to display in the InfoWindow
     var infowindow = new google.maps.InfoWindow( { content: contentString } );
     infowindow.open( map, marker );
     google.maps.event.addListener( marker, 'click', function() { infowindow.open( map, marker ); });

     var center;
     function calculateCenter() {
      center = map.getCenter();
     }

     google.maps.event.addDomListener(map, 'idle', function() {
      calculateCenter();
     });

     google.maps.event.addDomListener(window, 'resize', function() {
      map.setCenter(center);
     });

  }else {
       alert("Geocode was not successful for the following reason: " + status);
  }
});

Upvotes: 3

Views: 1481

Answers (1)

pesla
pesla

Reputation: 1254

There isn't a helper function that centers the map based on the location of the marker and the dimensions of the info window (as far as I know).

If your infoWindow has fixed dimensions, using the panBy method is probably the easiest way to implement what you need.

From the API reference:

panBy(x:number, y:number)

Changes the center of the map by the given distance in pixels. If the distance is less than both the width and height of the map, the transition will be smoothly animated. Note that the map coordinate system increases from west to east (for x values) and north to south (for y values).

A simple example:

// Use the property `center` to define the initial center of the map
var mapOptions = {};

// Render the map
var map = new google.maps.Map(document.getElementById('map'), mapOptions);

// Transition the center of the map by 0 pixels to the east, 
// and n pixels to the south, where n is half the height of
// the infoWindow
map.panBy(0, n);

If the infoWindow has dynamic dimensions, you'll have to query its dimensions first and then use the panBy method.

Would this work for you?

Upvotes: 2

Related Questions