google maps float pin at center and return location

半城伤御伤魂 提交于 2019-12-24 08:39:57

问题


I would like to keep the pin constant in the center of Google maps while the user can move the map and zoom around. Key is that the current GPS location of the pin (in the center still of course) recursively gets returned as value. I found this

Google Map API V2 - How do I keep a marker in the center of the screen while user is scrolling the map?

But I this does not return the current center coordinates. I was looking for a demo implementation with code but can't find anything, would greatly appreciate help.


回答1:


From this example on daftlogic.com, modified to use a marker instead of the crosshairs, put the center coordinates in an HTML element on the page.

Main points:

  1. marker is bound to the map's center
  2. the 'center_changed' is used to update the coordinates displayed on the page.

Working snippet:

function initialize() {
  var crosshairShape = {
    coords: [0, 0, 0, 0],
    type: 'rect'
  };
  var latlng = new google.maps.LatLng(54.62279178711505, -5.895538330078125);
  var myOptions = {
    zoom: 12,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    }
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  var marker = new google.maps.Marker({
    map: map,
  });
  document.getElementById('coordinates').innerHTML = "<b>center coordinates</b>: " + map.getCenter().toUrlValue(6)
  google.maps.event.addListener(map, 'center_changed', function() {
    document.getElementById('coordinates').innerHTML = "<b>center coordinates</b>: " + map.getCenter().toUrlValue(6);
  });
  marker.bindTo('position', map, 'center');
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
<div id="coordinates"></div>

working jsfiddle



来源:https://stackoverflow.com/questions/27195422/google-maps-float-pin-at-center-and-return-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!