【问题标题】:Make polyline to show on google map horizontally and zoom it to center coordinate使折线水平显示在谷歌地图上并将其缩放到中心坐标
【发布时间】:2021-12-30 22:51:39
【问题描述】:

我正在使用 Google Maps API JavaScript。我的用例是我需要在地图上绘制坐标(lat、lng)(创建标记)并通过折线将它们连接起来。坐标将非常接近,因此当我尝试绘制它们时,它们会隐藏在第一个标记后面。所以我找到了中心并尝试缩放,以便所有标记都在地图上可见。 我使用边界来找到中心,但我无法将其缩放到中心坐标。我用 ma​​p.fitBounds(latlng); 它适合屏幕上的坐标。 但我想要实现的是使折线(连接所有坐标)始终水平并将其缩放到中心坐标。

enter code herevar bounds = new google.maps.LatLngBounds();

for (i = 0; i < temp.length; i++) {
   bounds.extend(temp[i]);
}
var latlng = bounds.getCenter();
map.setCenter(latlng);

由于坐标总是不同的,折线将在任何方向,但我总是想在地图上水平显示它。 我得到什么: enter image description here

我想要达到的目标:

enter image description here

任何建议将不胜感激。 提前致谢。

【问题讨论】:

    标签: google-maps google-maps-api-3 google-maps-markers google-polyline


    【解决方案1】:

    我通过以下方式实现了这样的目标:

    1. 使用computeHeading() function of Geometry library 获取直线上从第一个坐标到最后一个坐标的角度。确保将 &amp;libraries=geometry 添加到您的 Maps JS 脚本标签中。
    2. 获得航向后,您可以使用map.setHeading() function 更改视角,经过一些测试,我可以看到您可以通过将其减去 90 度来实现水平视角。

    下面是sample code 和代码 sn-p:

    function initMap() {
      const map = new google.maps.Map(document.getElementById("map"), {
        center: {
          lat: 40.756795,
          lng: -73.954298
        },
        zoom: 16,
        tilt: 47.5,
        mapId: "90f87356969d889c",
      });
    
    
    //array of your points
     const markerCoordinates = [
       { lat: 40.758481, lng: -73.958269 },
        { lat:40.754649, lng: -73.949563 },
       
      ];
        
        //creating marker from your points
      for (let i = 0; i < markerCoordinates.length; i++) {
        const marker = markerCoordinates[i];
    
        new google.maps.Marker({
          position:marker,
          map,
        });
      }
       
       //creating polyline from your points
      const createdPolyline = new google.maps.Polyline({
        path: markerCoordinates,
        geodesic: true,
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 2,
      });
    
      createdPolyline.setMap(map);
      
      //get the heading(angle) of the first coordinate from the last coordinate
    const heading = google.maps.geometry.spherical.computeHeading(
        markerCoordinates[0],
        markerCoordinates[1]
      )
        
    //once you get the heading subtract it by 90 to get a horizontal view
       map.setHeading(heading-90)
    }
    
    

    【讨论】:

      猜你喜欢
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      相关资源
      最近更新 更多