search
HomeWeb Front-endJS TutorialUse OpenLayers3 to add map right-click menu_javascript skills

To add a right-click menu, first we need to monitor the right-click operation of the mouse. We know that the right-click event name of the mouse is contextmenu. When the mouse is on the html element and the right-click of the mouse is clicked, the contextmenu event will be triggered. In the callback function of the contextmenu event Just implement the corresponding display menu function.

So in openlayers, where do we start by adding this event to the map? First we have to understand the process of initializing the openlayers page.

openlayers initialization page process

Openlayers is also a front-end library, so it is definitely inseparable from the use of html. For example, we first need to place an html element displaying a map on the page, a div element (assuming its id attribute is set to "map", which will be referred to as as map div), and then specify this element when the map is initialized. Openlayers will first create a div element with class ol-viewport in this element, whose size remains the same as the map div, and then create a div element in the ol-viewport div. canvas element, render the requested map in this canvas element; secondly, a div element with class ol-overlaycontainer will be added to place the overlay; finally, a div element with class ol-overlaycontainer-stopevent will be added, mainly It is a control for placing openlayers. It was mentioned at the beginning of the previous article about adding custom extension controls. It is not the focus here and we will not introduce it in detail.

The final html dom structure is as shown below:

Use OpenLayers3 to add map right-click menu_javascript skills

Figure 1 The formed DOM structure

We will think of adding an event to this map div element, and then right-clicking to pop up the menu. This idea is natural and can indeed be realized. However, we must think about the following things and at least have an overall understanding of the matter before we start. We show After the menu comes out, certain operations are often performed based on the location of the corresponding map. Then the event object of our contextmenu contains the screen coordinates where the click occurred, but how to obtain the coordinates in the corresponding coordinate system in the map based on the screen coordinates will be compared. difficulty.

What’s the difficulty? There are mainly three points:

First of all, the coordinates contained in the event object are relative to the entire browser's viewport, page, or entire screen;
Secondly, the elements displaying the map are often of random sizes and positions;
Finally, the coordinate system of the screen and the coordinate system of the map are often completely different. How to convert the coordinates relative to the map elements into coordinates in the map coordinate system?

First, we need to get the coordinates of the event coordinates relative to the map div (the element containing the map), and then convert the coordinates relative to the map div into actual coordinates in the map. In the first step, we can obtain it through calculation, but the second step must be completed through openlayers, because only openlayers knows the coordinate system of the map best, which also has related functions in openlayers. Fortunately, in openlayers we can complete the above operations in one step, and only need one function: map.getEventCoordinate(event). In the specific implementation below, I will talk about this function in detail.

Let’s see how to implement it.

Detailed implementation of mouse right-click menu

For convenience, the code in the article uses JQuery.

The complete code of the example in the article can be viewed or downloaded in my GitHub. If it is useful, don’t forget to click the star.

Let’s add the right-click menu function step by step. We divide it into three steps:

Add contextmenu event to html element;

Get the corresponding click coordinates on the map;

Add a menu to the corresponding location on the map.

Add contextmenu event to html element

The right mouse button event of the html element is called contextmenu. This event is supported by all mainstream browsers. Don’t confuse the new html attribute contextmenu here. This attribute is currently only supported by firefox. We just use the oncontextmenu event. You can bind this event to any html element containing a map, and openlayers will handle coordinate conversion issues. As shown below, map.getViewport() will return the div element with class ol-viewport created when openlayers initializes the page, that is, the element that directly contains the map. Because browsers have default right-click menus, we need to cancel the default menu by calling e.preventDefault();:

$(map.getViewport()).on("contextmenu", function(event){
  e.preventDefault();
  // 书写事件触发后的函数
});

Get the corresponding click coordinates on the map

Getting the corresponding click coordinates on the map only requires one sentence, as follows,

var coordinate = map.getEventCoordinate(event);

      函数参数是 oncontextmenu 对应的事件对象,该函数包含对 map.getCoordinateFromPixel() 的调用,map.getCoordinateFromPixel() 参数为 ol.pixel,是一个坐标,数组格式[x, y],其实现中又调用了 ol.vec.Mat4.multVec2(),该函数完成处理坐标转换的实际工作。

地图相应位置添加菜单

      这里我们结合 overlay 添加菜单,之前的文章介绍过 overlay,这里就不再具体展开了。首先,我们在 html 页面添加一个目录,具体的 css 样式可以自己设定,想看完整源码的可以到我的 GitHub 中查看或者下载完整的代码:

<div id="contextmenu_container" class="contextmenu">
  <ul>
    <li><a href="#">设置中心</a></li>
    <li><a href="#">添加地标</a></li>
    <li><a href="#">距离丈量</a></li>
  </ul>
</div>

使用这个 html 元素初始化一个 overlay,并将 overlay 添加到地图中:

var menu_overlay = new ol.Overlay({
  element: document.getElementById("contextmenu_container"),
  positioning: 'center-center'
});
menu_overlay.setMap(map);

接下来,我们就可以在鼠标右键菜单的事件回调函数中,根据获取的地图坐标位置,设置 overlay 的显示位置:

menu_overlay.setPosition(coordinate);

菜单隐藏

      当我们鼠标点击右键,菜单出现,但是我们不能让菜单总是显示在地图中,这时我们可以添加鼠标左键单击,菜单消失功能,或者当选择某项功能时,菜单消失。这个比较容易实现,只要一句便可以实现,放在鼠标左键事件的回调函数或者菜单功能执行函数中就行,如下:

menu_overlay.setPosition(undefined);

总结

      这篇文章中,主要讲了 openlayers 初始化页面地图元素的过程,并介绍了在地图上实现“鼠标右键菜单功能”,和隐藏菜单的实现。我们并没有对菜单中的条目绑定事件,因为我们的重点在于实现右键菜单,对于菜单的条目要绑定什么功能,和普通的 javascript 事件绑定并无二致,所以没有展开。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)