Boris Dabetic
Boris Dabetic

Reputation: 113

Offset google map and fix marker

I'm trying to do something like this:

enter image description here

Where I have form on right half of screen and marker centered on left side of screen. Moving map - marker will stay in center of left side, and I will get LatLng from the marker(Visualy, but that is offseted center) on Map move.

For now I have centered marker on map and I can move map and get LatLng from center.

This is script that do that:

            var map = null;
            var marker;

            function showlocation() {
                if ("geolocation" in navigator) {
                    /* geolocation is available */
                    // One-shot position request.
                    navigator.geolocation.getCurrentPosition(callback, error);
                } else {
                    /* geolocation IS NOT available */
                    console.warn("geolocation IS NOT available");
                }
            }

            function error(err) {
                console.warn('ERROR(' + err.code + '): ' + err.message);
            };

            function callback(position) {

                var lat = position.coords.latitude;
                var lon = position.coords.longitude;
                document.getElementById('default_latitude').value = lat;
                document.getElementById('default_longitude').value = lon;
                var latLong = new google.maps.LatLng(lat, lon);
                map.setZoom(16);
                map.setCenter(latLong);
            }
           // google.maps.event.addDomListener(window, 'load', initAutocomplete);


            function initAutocomplete() {
                var mapOptions = {
                    center: new google.maps.LatLng(42.4405026181028, 19.24323633505709),
                    zoom: 16,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                map = new google.maps.Map(document.getElementById("map"),
                    mapOptions);
                google.maps.event.addListener(map, 'center_changed', function () {
                    document.getElementById('default_latitude').value = map.getCenter().lat();
                    document.getElementById('default_longitude').value = map.getCenter().lng();

                });
                $('<div/>').addClass('centerMarker').appendTo(map.getDiv())
                    .click(function () {
                        var that = $(this);
                        if (!that.data('win')) {
                            that.data('win', new google.maps.InfoWindow({
                                content: 'this is the center'
                            }));
                            that.data('win').bindTo('position', map, 'center');
                        }
                        that.data('win').open(map);
                    });

And I have marker centered in CSS:

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

I just need to offset all of this for 25% to the left from the center and keep 50% of right screen for the form.

Upvotes: 1

Views: 1842

Answers (1)

Emmanuel Delay
Emmanuel Delay

Reputation: 3679

I skipped most of your question and focus on the title (and your last line of text). I wrote a function that, rather than map.setCenter(marker.getPosition()), instead I read the width of the map, not in meter but in degrees. And then I set the center to a point at the right of the marker. The offset is 1/4 the width of the map.

So we need to find that point, then center on that point. I put it in a function, so that you can use it in your code (at first glance of your code).

Is this useful to you? As an example I picked a few markers with names without accents that are not on my keyboard.

<head>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=INSERT_YOU_API_KEY_HERE" async defer></script>
<script>
var map;
var markers = [];
var venues = [
  {name: 'Hard Rock Cafe', lat: 42.440872894381336, lng: 19.243852126140837},
  {name: 'Hospital', lat: 42.43778998082812, lng: 19.24720468486862},
  {name: 'CRNE Gore', lat: 42.443011545449124, lng: 19.240621744796726},
];
function initMap() {
  var mapOptions = {
    center: new google.maps.LatLng(42.4405026181028, 19.24323633505709),
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map"), mapOptions);
  for(var i in venues) {
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(venues[i].lat, venues[i].lng),
      title: venues[i].name,
      map: map
    });
    markers.push(marker);
    google.maps.event.addListener(marker, 'click', function () {
      var markerPosition = this.getPosition();
      var newCenter = centerWithOffset(markerPosition);
      map.setCenter(newCenter);
      // if you need to know which marker was clicked on:
      // you might need this index to set the data of the infoWindow
      var i = markers.indexOf(this);
      document.getElementById("display").innerHTML = "marker " + i + " was clicked on";
    });
  }
  google.maps.event.addListener(map, 'center_changed', function () {
    document.getElementById("display").innerHTML = map.getCenter().toString();
  });
}
function centerWithOffset(markerPosition) {
  // rather than this center, we want a new center point that is offset by 1 / 4 of the width of the map to the right.
  // @see https://stackoverflow.com/questions/6910847/get-boundaries-longitude-and-latitude-from-current-zoom-google-maps
  var bounds = map.getBounds();
  var ne = bounds.getNorthEast(); // LatLng of the north-east corner
  var sw = bounds.getSouthWest(); // LatLng of the south-west corder
  // calculate width
  var width = ne.lng() - sw.lng();
  // now apply this offset
  var newCenter = new google.maps.LatLng(
    markerPosition.lat(),
    (markerPosition.lng() + (width / 4))
  );
  return newCenter;
}
</script>
<style>
#map {
  width: 700px;
  height: 300px;
}
</style>
</head>
<body>
  <div id="map"></div>
  <div id="display"></div>
</body>

Upvotes: 3

Related Questions