Add a marker to an image in javascript?
Yes, it is possible.
Although it's totally doable with just javascript, I would use some kind of library like JQuery.
The approach would be to have an img-element with your marker, and then add a click-handler to the image you want to use as your "map" which moves your marker to where the element was clicked.
Here is an untested example:
<img src="marker.png" id="marker" style="display: none; position: absolute;" />
<img src="map.png" id="map" />
<script type="text/javascript">
$('#map').click(function(e)
{
$('#marker').css('left', e.pageX).css('top', e.pageY).show();
// Position of the marker is now e.pageX, e.pageY
// ... which corresponds to where the click was.
});
</script>
Edit: And this is totally possible without JQuery too, of course. Below is a code-example of just that.
<img src="marker.png" id="marker" style="display: none; position: absolute;" />
<img src="map.png" id="map" />
<script type="text/javascript">
document.getElementById('map').onclick = function(e)
{
with(document.getElementById('marker'))
{
style.left = e.pageX;
style.top = e.pageY;
style.display = 'block';
}
// Here you forward the coordinates e.pageX, e.pageY
// ... to whatever function that needs it
};
</script>
Richard
Updated on July 09, 2022Comments
-
Richard almost 2 years
Anyone know how I can add a marker to an image (not a map) in Javascript?
Ideally I'd like a handler that behaves much like adding a marker to a map - i.e. onclick causes a marker to be displayed at the point that was clicked, and returns the x/y pixel coordinates of the point that was clicked.
Is this possible?
Cheers Richard
-
Richard over 14 yearsNot so fast... pageX and pageY give me the pixel position relative to the top left corner of the page. Is there any way to get the pixel position within the image? If not then I guess I can figure out the pixel position of the corner of the image and subtract, but it seems a bit messy. Thanks.
-
Martin Nycander over 14 yearsThere are a bunch of different non-standardized attributes which specifies coordinates, but they seem to be very browser-specific. To avoid that I would subtract the position of the image as you said.
-
Nihar over 10 yearsThanks a lot to both of u, Richard and Martin Nycander
-
Oscar Barrett over 7 yearsMouseEvent.offsetX and MouseEvent.offsetY are supported in all major browsers, and from IE6 onwards. developer.mozilla.org/en-US/docs/Web/API/MouseEvent/…