Displaying crosshairs in the center of a JavaScript Google Map

Tags: , ,



I’d like to display a crosshair/reticule that’s fixed in the center of a Google Map, just as Wikimapia.org do. Unfortunately they are using v2 of the API and I’m using v3.

The crosshair should remain fixed in the center as the user pans the map around.

There’s no CENTER option for the ControlPosition enum, so I imagine any solution will be a bit hacky.

I’ve tried to overlay it as a div outside of the map, but I haven’t managed to get it to display on top of the map — it seems to get trumped in a z-order showdown.

Answer

The given solution didn’t work for me, because the overlying div creates a dead spot in the map. A better solution for my project, using the Google Maps JavaScript API V3, was to create the reticle on the map as a marker with a 1 pixel rectangle shape. Then use the maps bounds_changed event to recenter the marker.

Reticle image is 63 x 63 png. (images/reticle.png)

Define the marker image and shape…

  var reticleImage = new google.maps.MarkerImage(
    'images/reticle.png',            // marker image
    new google.maps.Size(63, 63),    // marker size
    new google.maps.Point(0,0),      // marker origin
    new google.maps.Point(32, 32));  // marker anchor point
  var reticleShape = {
    coords: [32,32,32,32],           // 1px
    type: 'rect'                     // rectangle
  };

After creation of our map (main_map) we add the marker…

  reticleMarker = new google.maps.Marker({
    position: latlng,
    map: main_map,
    icon: reticleImage, 
    shape: reticleShape,
    optimized: false,
    zIndex: 5
  });

Here the var latlng is the same LatLng object used to create main_map. The zIndex should be greater than any other marker zIndex’s, to keep the reticle on top.

Then we add an event handler to be called when the map bounds_changed is fired.

  google.maps.event.addListener(main_map, 'bounds_changed', centerReticle);

and finally we have the centerReticle() function.

  function centerReticle(){
    reticleMarker.setPosition(main_map.getCenter());
  }

Since we’re not doing anything else with the ‘bounds_changed’ event we can tidy up the code by passing an anonymous function to the addListener call… This keeps us from having to define the centerReticle() function.

  google.maps.event.addListener(main_map, 'bounds_changed',
      function(){reticleMarker.setPosition(main_map.getCenter());});

It actually works pretty slick. I hope this helps others.

Thanks.

Skip



Source: stackoverflow