Nazeem
Nazeem

Reputation: 764

Let arrow marker point in the direction of another marker

I'm making a Google Maps application where a user can search for a location. This location must point into the direction of a predefined marker.

Given the following pieces of code:

The predefined marker:

      var station = new google.maps.LatLng(52.375401, 5.218824);

      var stationMarker = new google.maps.Marker({
        position:   station,
        map:        map,
        });

The marker that will be placed on the location that the user searched:

      var direction = new google.maps.LatLng(52.376423, 4.887234);

      var directionMarker = new google.maps.Marker({
        position:   direction,
        map:        map,
        draggable:  false,
        title:      "test"
        });

      directionMarker.setIcon(({
        path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
        scale: 6
        }));

How can I make sure that the direction marker (i.e the marker from the user search result) always points to the predefined marker?

I'm making use of the Google Maps API v3.

I've created a jsFiddle, which you can find here

Upvotes: 4

Views: 6780

Answers (1)

MrUpsidown
MrUpsidown

Reputation: 22490

Ok here you go:

  1. Use the google.maps.SymbolPath.FORWARD_CLOSED_ARROW so that it points to the north.
  2. Add the Geometry library to be able to compute a heading.
  3. Use the rotation parameter on your direction icon.

Here is how to compute the heading from your direction marker to the station:

var heading = google.maps.geometry.spherical.computeHeading(direction,station);

Then use it to rotate your icon accordingly:

directionMarker.setIcon({
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
    scale: 6,
    rotation: heading
});

You also had one unnecessary pair of () in the above code which I have removed.

JSFiddle demo

Upvotes: 6

Related Questions