2015-12-29 23 views
2

我已經創建了一個函數,它是以google map爲中心的,但是我需要把它放在上面,因爲我的描述窗口是不可見的。如何讓谷歌地圖不居中,但稍高一點?

這是圖片它的外觀:

enter image description here

而且這是圖片我多麼想看看:

enter image description here

這裏是一個JS腳本。

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); 
    } 
}); 
+1

我從來沒有真正使用Google地圖API,但是不能僅僅將調用中使用的位置碰撞到map.setCenter?像0.00001添加一個小的偏移量,可能只是做伎倆? –

+0

@ChristiaanRakowski:您可能想要計算從地圖視口大小和縮放級別的偏移量,但本質上,您是對的。 (自v2以來,我並沒有過多地涉及到GMaps API,所以我沒有把它作爲答案,因爲它不夠具體;但同樣的原理適用於任何地圖平臺。) – Piskvor

+0

剛剛嘗試過使用靜態拉特朗,可能是因爲它發生了。不確定,但我們可以嘗試一次。 –

回答

1

根據標記的位置和信息窗口的尺寸(據我所知)沒有幫助函數使地圖居中。

如果您的infoWindow有固定的尺寸,使用panBy方法可能是實現您所需要的最簡單的方法。

the API reference

panBy(x:number, y:number)

變更地圖的由以像素爲給定的距離的中心。如果距離小於地圖的寬度和高度,則過渡將平滑動畫。請注意,地圖座標系統從西向東(對於x值)和從北到南(對於y值)增加。

一個簡單的例子:

// 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); 

如果infoWindow具有動態標註,你必須首先查詢它的尺寸,然後使用panBy方法。

這會適合你嗎?

+0

是的,它適用於我。謝謝你的幫助 :) –