How to position viewport to top center marker google maps

问题描述 投票:0回答:3

我是谷歌地图的新手,以下是谷歌地图的代码片段 标记位于屏幕中间,但我怎样才能出现在屏幕的顶部中心(如图所示的顶部中间)。

function initMap() {
  const myLatLng = { lat: -25.363, lng: 131.044 };
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: myLatLng,
  });

  new google.maps.Marker({
    position: myLatLng,
    map,
    title: "Hello World!",
  });
}

window.initMap = initMap;

javascript google-maps-markers
3个回答
0
投票

要将标记定位在屏幕的顶部中心,您可以通过修改其锚点来调整标记的位置。默认情况下,标记的锚点是它的中心,但您可以在创建标记时通过指定锚点选项将其更改为顶部中心。


0
投票

简单的,到指定位置可以使用

Map.panTo()
方法,设置缩放级别可以使用
Map.setZoom()
方法。

你可以测试它,看看它是否对你有用,如果你想要任何改变,请告诉我,我会做的。

function initMap() {
  const myLatLng = { lat: -25.363, lng: 131.044 };
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: myLatLng,
  });

  const marker = new google.maps.Marker({
    position: myLatLng,
    map,
    title: "Hello World!",
  });

  // Set the map center to the marker position
  map.panTo(myLatLng);

  // Set the zoom level to 12
  map.setZoom(12);
}

window.initMap = initMap;
<!DOCTYPE html>
<html>
  <head>
    <title>Google Maps Example</title>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>
    <style>
      #map {
        height: 400px;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>


0
投票

PanTo()
https://developers.google.com/maps/documentation/javascript/reference/map#Map.panTo

此函数用于设置地图的中心位置:

panTo(latLng)

参数: latLng: LatLng|LatLngLiteral 地图新的中心纬度/经度.

返回值:无

将地图的中心更改为给定的 LatLng。如果变化小于地图的宽度和高度,过渡将平滑动画。


所以这会让你根据标记设置中心位置。

function initMap() {
  const myLatLng = { lat: -25.363, lng: 131.044 };
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: myLatLng,
  });

  new google.maps.Marker({
    position: myLatLng,
    map,
    title: "Hello World!",
  });

  // map position set to center according to marker position
  map.panTo(myLatLng);
}

window.initMap = initMap;
© www.soinside.com 2019 - 2024. All rights reserved.