javascript 有没有办法将 Google 地图标记始终固定在其地图的中心?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19327254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:11:17  来源:igfitidea点击:

Is there a way to Fix a Google Maps Marker to the Center of its Map always?

javascriptgoogle-mapsmobilegoogle-maps-api-3

提问by jlstr

To be more precise, what I try to accomplish is that while I Draga Google Map there's a Google Maps Markerthat stays fixed at the center of the map at all times. This will improve User experience in my opinion, This is how I'm doing it now:

更准确地说,我试图完成的是,当我拖动Google 地图时,有一个 Google 地图标记始终固定在地图的中心。我认为这将改善用户体验,这就是我现在的做法:

var map, marker, options;

options = {
  center: new google.maps.LatLng(latitude, longitude),
  zoom: 15,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  mapTypeControl: false,
  overviewMapControl: false,
  zoomControl: true,
  draggable: true
};

map = new google.maps.Map(mapContainer, options);

marker = new google.maps.Marker({
  position: new google.maps.LatLng(latitude, longitude),
  map: map,
  animation: google.maps.Animation.DROP
});

//This line is what makes the Marker stick to the center of the map
marker.bindTo('position', map, 'center');

The problem I have with the code above is that.. When I drag the map underneath the Marker it's not smooth enough, ie. the Marker makes a wierd jumpfrom the 'last' center to the 'new' center when dragging ends. (this is more noticeable on mobile devices), Therefore what I need is that the Marker is Really permanently fixedto the Center of its Map.

我在上面的代码中遇到的问题是.. 当我将地图拖到标记下方时,它不够平滑,即。拖动结束时,标记会从“最后一个”中心奇怪地跳到“新”中心。(这在移动设备上更明显),因此我需要的是标记真的永久固定在其地图的中心。

Is there a way to get this done? (I think I've seen this in a web-site once)

有没有办法做到这一点?(我想我曾经在一个网站上看到过这个)

Let me know If you guys can help me.

如果你们能帮助我,请告诉我。

Thank you.

谢谢你。

回答by Itay Grudev

Rather than injecting an HTML component as suggested in @Dr.Molle'sanswer, why don't you use a CSS only solution.

与其像@Dr.Molle 的回答中所建议的那样注入 HTML 组件,不如使用仅使用 CSS 的解决方案。

It is simpler, more efficient and doesn't require you to even touch the DOM (so there won't be any problems if Google changes their implementation).

它更简单、更高效,甚至不需要您接触 DOM (因此如果 Google 更改其实现就不会有任何问题)

Also since Google Maps don't apply any styles on the container element (#map)the solution is pretty safe.

此外,由于 Google 地图不会在容器元素( #map)上应用任何样式,因此该解决方案非常安全。

#map {
    position: relative;
}

#map:after {
    width: 22px;
    height: 40px;
    display: block;
    content: ' ';
    position: absolute;
    top: 50%; left: 50%;
    margin: -40px 0 0 -11px;
    background: url('https://maps.gstatic.com/mapfiles/api-3/images/spotlight-poi_hdpi.png');
    background-size: 22px 40px; /* Since I used the HiDPI marker version this compensates for the 2x size */
    pointer-events: none; /* This disables clicks on the marker. Not fully supported by all major browsers, though */
}

Here is a jsFiddle.

这是一个jsFiddle

回答by Dr.Molle

A different approach, that did not use a real google.maps.Marker:

一种不同的方法,没有使用真正的google.maps.Marker:

after the map has been initialized, inject a div into the map-container, give it a className(e.g. centerMarker), the further things will be done via CSS:

在地图初始化后,将一个 div 注入到地图容器中,给它一个类名(例如centerMarker),进一步的事情将通过 CSS 完成:

.centerMarker{
  position:absolute;
  /*url of the marker*/
  background:url(http://maps.gstatic.com/mapfiles/markers2/marker.png) no-repeat;
  /*center the marker*/
  top:50%;left:50%;

  z-index:1;
  /*fix offset when needed*/
  margin-left:-10px;
  margin-top:-34px;
  /*size of the image*/
  height:34px;
  width:20px;

  cursor:pointer;
}

Demo: http://jsfiddle.net/doktormolle/jcHqt/

演示:http: //jsfiddle.net/doktormolle/jcHqt/

回答by Mahlatse Makalancheche

You can listen to the center changes via something like below, you will just have to update your view:

您可以通过以下方式收听中心更改,您只需要更新您的视图:

google.maps.event.addListener(map, "dragend", function() {
   console.log(map.getCenter().toUrlValue());
});

Current main used solution is for bringing up the InfoWindow only when onclick, I needed it on all the time like it is on Uber, so I replaced even the InfoWindow to a css only solution, updating the view the normal angular route with Ionic

当前主要使用的解决方案是仅在 onclick 时显示 InfoWindow,我一直需要它,就像在 Uber 上一样,所以我甚至将 InfoWindow 替换为仅 css 的解决方案,使用 Ionic 更新视图的正常角度路线

HTML:

HTML:

 <ion-content >
   <div id="map" data-tap-disabled="true">
  </div>
  <div id="centerInfoBubble">
    <span>{{locationCtrl.coordinates}}</span>
  </div>
  <div id="centerMarker"></div>
 </div>
 </ion-content>

CSS:

CSS:

#map {
 width: 100%;
 height: 100%;
}
#centerInfoBubble {
  position: absolute;
  /*center the marker*/
 top: 38%;
 left: 22.5%;
 z-index: 1;
 width: 50%;
 height: 6%;
 border-radius: 20px;
 border: 1px solid #111;
 background-color: #444444;
 color: #fff;
 padding: 0.5% 5%;
 cursor: pointer;
}
#centerMarker {
 position: absolute;
 /*url of the marker*/
 background: url(http://maps.gstatic.com/mapfiles/markers2/marker.png) no-repeat;
 /*center the marker*/
 top: 45%;
 left: 45%;
 z-index: 1;
 height: 10%;
 width: 10%;
 cursor: pointer;
}

Controller:

控制器:

myModule.controller('LocationCtrl',['$scope','$cordovaGeolocation',function($scope,$cordovaGeolocation){
$scope.locationCtrl = {
    coordinates : null
};
var options = {timeout: 10000, enableHighAccuracy: true};
var marker;

$cordovaGeolocation.getCurrentPosition(options).then(function(position){

    var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

    var mapOptions = {
            center : latLng,
            zoom : 16,
            mapTypeId : google.maps.MapTypeId.ROADMAP,
            mapTypeControl : false,
            streetViewControl : false,
            zoomControl : false
    };

    $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
    $scope.locationCtrl.coordinates = $scope.map.getCenter().toUrlValue();

    google.maps.event.addListener($scope.map, "dragend", function() {
        $scope.locationCtrl.coordinates = $scope.map.getCenter().toUrlValue();
        $scope.$apply();
    });

}, function(error){
console.log("Could not get location");
});

}]);

I don't know if there are performance issues with this yet, but looks quite smooth on the device, hope it helps someone

我不知道这是否存在性能问题,但在设备上看起来很流畅,希望对某人有所帮助

回答by mkkr

If this can help, what I did is :

如果这有帮助,我所做的是:

const myLatLng = {lat: 42, lng: 42};

map = new google.maps.Map(document.getElementById('map'), {
  center: myLatLng,
  zoom: 14,
});

marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
});

map.addListener('center_changed', () => {
  marker.setPosition(map.getCenter())
})

回答by brook

You can use google map drag event:

您可以使用谷歌地图拖动事件:

google.maps.event.addListener(map, 'dragend', function() {
    marker.setPosition(map.getCenter()); 
} );

回答by Galal

Here is how to do it as smooth as possible, and you can also get latlng at the same time.

以下是如何尽可能顺利地进行,您还可以同时获得 latlng。

    var map;
    var marker;
    var myInterval = setInterval(move, 1000 / 60);


    function handleEvent(event) {
        var latlng = map.getCenter();
        document.getElementById('lat').value = latlng.lat();
        document.getElementById('lng').value = latlng.lng();
    }



    // Initialize and add the map
    function initMap() {
        var uluru = { lat: -25.344, lng: 131.036 };
        map = new google.maps.Map(
            document.getElementById('map'), { zoom: 4, center: uluru });
        marker = new google.maps.Marker({
            position: uluru,
            map: map,
            animation: google.maps.Animation.DROP
        });
        map.addListener('center_changed', handleEvent);
        document.getElementById('lat').value = "-25.344";
        document.getElementById('lng').value = "131.036";
    }


    function move(){
        try {
          var latlngMAP = map.getCenter();
          var latlngMARKER = marker.getPosition();
          tempLAT = lerp (latlngMARKER.lat(), latlngMAP.lat(), 0.1);
          tempLNG = lerp (latlngMARKER.lng(), latlngMAP.lng(), 0.1);
         var latlng = { lat: tempLAT, lng: tempLNG };
          marker.setPosition(latlng);
        } catch{
        }
    }
    function lerp(start, end, amt) {
         return (1-amt)*start+amt*end
    }