google maps float pin at center and return location

3k views Asked by At

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

There are 1 answers

1
geocodezip On

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