How it works…

Google allows you to embed Google Maps in a web page using their JavaScript library, called the Google Maps API. Through Qt's WebEngine module, we can embed Google Maps in our C++ project by loading an HTML file to our webview widget, which uses the Google Maps API. The only downside of this method is that we cannot load the map when there is no internet connection.

The Google API can be called by your website as Google allows it. Choose the free API if your plan is for heavier traffic.

Go to https://console.developers.google.com to get a free key and replace YOUR_KEY_HERE in the JavaScript source path with the API key you obtained from Google.

We must define a <div> object, which serves as a container for the map. Then, when we initialize the map, we specify the ID of the <div> object so that the Google Maps API knows which HTML element to look for when embedding the map. By default, we set the center of the map to the coordinates of New York and set the default zoom level to 6. Then, we add an event listener that gets triggered when the zoom level of the map changes. Remove the double slashes, //, from the code to see it in action.

After that, we added a marker to the map through JavaScript. The marker also has an event listener attached to it, which will trigger the panTo() function when the marker is clicked. It basically pans the map view to the marker that has been clicked. Although we have added the drawing manager to the map (the icon buttons beside the Map and Satellite buttons), which allows users to draw any type of shape on top of the map, it's also possible to add the shapes manually using JavaScript, similar to how we added the marker in step 12, in the How to do it... section.

Lastly, you may have noticed that the headers are added to mainwindow.cpp instead of mainwindow.h. This is totally fine unless you are declaring class pointers in mainwindow.h—then you have to include those headers in it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset