Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

javascript - Is there a way to Fix a Google Maps Marker to the Center of its Map always?

To be more precise, what I try to accomplish is that while I Drag a Google Map there's a Google Maps Marker that stays fixed at the center of the map at all times. This will improve User experience in my opinion, This is how I'm doing it now:

var map, marker, options;

options = {
  center: new google.maps.LatLng(latitude, longitude),
  zoom: 15,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  mapTypeControl: false,
  overviewMapControl: false,
  zoomControl: true,
  draggable: true
};

map = new google.maps.Map(mapContainer, options);

marker = new google.maps.Marker({
  position: new google.maps.LatLng(latitude, longitude),
  map: map,
  animation: google.maps.Animation.DROP
});

//This line is what makes the Marker stick to the center of the map
marker.bindTo('position', map, 'center');

The problem I have with the code above is that.. When I drag the map underneath the Marker it's not smooth enough, ie. the Marker makes a wierd jump from the 'last' center to the 'new' center when dragging ends. (this is more noticeable on mobile devices), Therefore what I need is that the Marker is Really permanently fixed to the Center of its Map.

Is there a way to get this done? (I think I've seen this in a web-site once)

Let me know If you guys can help me.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Rather than injecting an HTML component as suggested in @Dr.Molle's answer, why don't you use a CSS only solution.

It is simpler, more efficient and doesn't require you to even touch the DOM (so there won't be any problems if Google changes their implementation).

Also since Google Maps doesn't apply any styles on the container element (#map) the solution is pretty safe.

#map {
    position: relative;
}

#map:after {
    width: 22px;
    height: 40px;
    display: block;
    content: ' ';
    position: absolute;
    top: 50%; left: 50%;
    margin: -40px 0 0 -11px;
    background: url('https://maps.gstatic.com/mapfiles/api-3/images/spotlight-poi_hdpi.png');
    background-size: 22px 40px; /* Since I used the HiDPI marker version this compensates for the 2x size */
    pointer-events: none; /* This disables clicks on the marker. Not fully supported by all major browsers, though */
}

Here is a jsFiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...