【问题标题】:Is there a way to Fix a Google Maps Marker to the Center of its Map always?有没有办法始终将 Google 地图标记固定到其地图的中心?
【发布时间】:2013-10-20 01:43:23
【问题描述】:

更准确地说,我试图实现的是,当我拖动 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');

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

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

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

谢谢。

【问题讨论】:

  • 您是否尝试将 google.maps.Marker 的位置绑定到 google.maps.Map 对象的 center 属性?
  • 否定,先生,我在阅读文档后能想到的唯一解决方案就是您在那里看到的解决方案。如果你能教我如何做你所描述的,我将不胜感激。
  • 其实我觉得我现在正在做的事情是这样的?对吗?
  • 是的。和it works for me。它不适合你吗?
  • 不是标记在@geocodezip给出的链接上跳转

标签: javascript google-maps mobile google-maps-api-3


【解决方案1】:

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

地图初始化后,在地图容器中注入一个div,给它一个className(例如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;
}

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

【讨论】:

  • 看起来很结实。我会尽快试一试,谢谢楼主。这似乎正是我所需要的。待机。
  • 不错的答案,但是当我们移动地图时这可能会自动加载地图吗?还有一件事是我们可以在将地图拖动到新位置后获得位置。
  • 这不会帮助您获得 lat 和 lng。将上述方法与 map.addListener('center_changed',callback() {});也可以获取坐标。
  • 很好的答案这正是我想要的,但我想用我的自定义标记替换标记,当我尝试替换它时,它会消失,请帮助
  • @Alfred Alfizo Mosima:如果没有看到您的尝试,很难帮助您。您可能必须修改 CSS 的 width/height/top/left 。使用头像的示例(328x328px)jsfiddle.net/doktormolle/0fmdasrg
【解决方案2】:

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

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

当前主要使用的解决方案是仅在单击时调出 InfoWindow,我一直需要它,就像在 Uber 上一样,所以我什至将 InfoWindow 替换为仅 css 的解决方案,更新视图的正常角度路线离子

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:

#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;
}

控制器:

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");
});

}]);

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

【讨论】:

  • 我会将所有控制器垃圾放入服务或工厂,具体取决于您的角度方法,我将其放入服务中,将其包装在 init 函数中,然后从控制器调用服务的 init 函数使用 $timeout 进行控制器初始化
【解决方案3】:

而不是像 @Dr.Molle's 回答中建议的那样注入 HTML 组件,为什么不使用纯 CSS 解决方案。

它更简单、更高效,甚至不需要你触摸 DOM(所以如果 Google 改变它们的实现也不会有任何问题)

此外,由于 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 */
}

这是jsFiddle

【讨论】:

  • 智能纯 CSS 方法!从来没有想过以这种方式使用 css peudo 元素。谢谢。
  • 更好的方法。我对注入方法感到畏缩,尤其是因为它使用了 JQuery。很高兴我向下滚动并找到了您的答案。
【解决方案4】:

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

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())
})

【讨论】:

  • 这是一个很好的解决方案,因为它标记允许车轮事件向地图传递,但是它有滞后并且标记在拖动时会跳跃和振动。
【解决方案5】:

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

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

【讨论】:

    【解决方案6】:

    这里是如何做到尽可能流畅,你也可以同时得到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
        }
    

    【讨论】:

      【解决方案7】:

      在这里我添加了带有固定销的地理位置按钮地图,以准确定位您的位置

      试试看:)

       
      function loadScript(src,callback)
      { 
          var script = document.createElement("script");
          script.type = "text/javascript";
          if(callback)script.onload=callback;
          document.getElementsByTagName("head")[0].appendChild(script);
          script.src = src;
      }
        
        loadScript('https://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initialize');
      
      function initialize() 
      		{   
          map = new google.maps.Map(document.getElementById('map_canvas'), {
                zoom: 13, 
              });
      latitudeTxt=document.getElementById('latitude');
      longitudeTxt=document.getElementById('longitude');
              marker = new google.maps.Marker({
                map: map,
                draggable: false,
                animation: google.maps.Animation.DROP,
                position: {lat: 59.327, lng: 18.067}
              });
              var position = marker.getPosition();
              if(typeof position !== 'undefined')
              {
                  map.setCenter(marker.getPosition());
              }
       			
            	map.addListener('center_changed', () => {
                
                 marker.setPosition(map.getCenter())
                  //get current location when we move the map 
                  var NewMapCenter = map.getCenter();
                 var latitude = NewMapCenter.lat();
      					var longitude = NewMapCenter.lng();
                 latitudeTxt.innerHTML =latitude;
                 longitudeTxt.innerHTML =longitude;
              })
              
              addYourLocationButton(map, marker);
      		}
      
       function geolocate() 
          {
              if (navigator.geolocation) {
                  navigator.geolocation.getCurrentPosition(function(position) {
                  var geolocation = {
                      lat: position.coords.latitude,
                      lng: position.coords.longitude
                  };
                  map.setCenter(geolocation); 
                  });
              }
          }
       
       function addYourLocationButton (map, marker) 
      {
          var controlDiv = document.createElement('div');
      
          var firstChild = document.createElement('button');
          firstChild.style.backgroundColor = '#fff';
          firstChild.style.border = 'none';
          firstChild.style.outline = 'none';
          firstChild.style.width = '28px';
          firstChild.style.height = '28px';
          firstChild.style.borderRadius = '2px';
          firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
          firstChild.style.cursor = 'pointer';
          firstChild.style.marginRight = '10px';
          firstChild.style.padding = '0';
          firstChild.title = 'Your Location';
          controlDiv.appendChild(firstChild);
      
          var secondChild = document.createElement('div');
          secondChild.style.margin = '5px';
          secondChild.style.width = '18px';
          secondChild.style.height = '18px';
          secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-2x.png)';
          secondChild.style.backgroundSize = '180px 18px';
          secondChild.style.backgroundPosition = '0 0';
          secondChild.style.backgroundRepeat = 'no-repeat';
          firstChild.appendChild(secondChild);
      
          google.maps.event.addListener(map, 'center_changed', function () {
              secondChild.style['background-position'] = '0 0';
          });
      
          firstChild.addEventListener('click', function () {
              var imgX = 0,
                  animationInterval = setInterval(function () {
                      imgX = -imgX - 18 ;
                      secondChild.style['background-position'] = imgX+'px 0';
                  }, 500);
      
              if(navigator.geolocation) {
                  navigator.geolocation.getCurrentPosition(function(position) {
                      var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                      map.setCenter(latlng);
                      clearInterval(animationInterval);
                      secondChild.style['background-position'] = '-144px 0';
                  });
              } else {
                  clearInterval(animationInterval);
                  secondChild.style['background-position'] = '0 0';
              }
          });
      
          controlDiv.index = 1;
          map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
      }
      body,html,#map_canvas{height:100%;margin:0;}
      #map_canvas .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;
      }
      <html>
      <body>
      <div id="map_canvas" style="height:400px"></div>
      <div id="latitude">latitude</div>
      <br/>
      <div id="longitude">longitude</div>
      </body> 
      </html>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-04
        • 1970-01-01
        • 2016-04-16
        • 1970-01-01
        • 2012-11-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多