Embedding Google Maps in your project

In this example, we will learn how to embed Google Maps in our project through Qt's WebEngine module. This example doesn't focus much on Qt and C++, but rather on the Google Maps API in HTML code.

How to do it…

Let's create a program that displays Google Maps by following these steps:

  1. First, create a new Qt Widgets Application project and remove the status bar, menu bar, and tool bar.
  2. Then, open up your project file (.pro) and add the following modules to your project:
    QT += core gui webengine webenginewidgets
    
  3. Next, open up mainwindow.ui and add a vertical layout to the canvas. Then, select the canvas and click the Lay Out Vertically button on top of the canvas. You will get something like this:
    How to do it…
  4. Then, open up mainwindow.cpp and add the following headers to the top of the source code:
    #include <QtWebEngineWidgets/QWebEngineView>
    #include <QtWebEngineWidgets/QWebEnginePage>
    #include <QtWebEngineWidgets/QWebEngineSettings>
  5. After that, add the following code to the MainWindow constructor:
    MainWindow::MainWindow(QWidget *parent) :
      QMainWindow(parent),
      ui(new Ui::MainWindow)
    {
      ui->setupUi(this);
      QWebEngineView* webview = new QWebEngineView;
      QUrl url = QUrl("qrc:/map.html");
      webview->page()->load(url);
      ui->verticalLayout->addWidget(webview);
    }
  6. Then, go to File | New File or Project and create a Qt resource file (.qrc). We will add an HTML file to our project called map.html:
    How to do it…
  7. Once you're done with that, open up map.html with your favorite text editor. It's not recommended to open an HTML file using Qt Creator, as it does not provide any color coding for HTML syntax.
  8. After that, we will start writing the HTML code by declaring the important tags, such as <html>, <head>, and <body>, like so:
    <!DOCTYPE html>
    <html>
      <head>
      </head>
      <body ondragstart="return false">
      </body>
    </html>
  9. Then, add a <div> tag to the body and set its ID as map-canvas:
    <body ondragstart="return false">
      <div id="map-canvas" />
    </body>
  10. After that, add the following code to the head of the HTML document:
    <meta name="viewport" content="initial-scale=1.0,user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    </style>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&libraries=drawing"></script>
  11. Then, add the following code, also to the head of the HTML document, right at the bottom of the code we inserted in the previous step:
    <script type="text/javascript">
      var map;
      function initialize()
      {
        // Add map
        var mapOptions =
        {
          center: new google.maps.LatLng(40.705311, -74.2581939),
            zoom: 6
        };
    
        map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
    
        // Add event listener
        google.maps.event.addListener(map, 'zoom_changed', function()
        {
          //alert(map.getZoom());
        });
    
        // Add marker
        var marker = new google.maps.Marker(
        {
          position: new google.maps.LatLng(40.705311, -74.2581939),
            map: map,
            title: "Marker A",
        });
        google.maps.event.addListener(marker, 'click', function()
        {
          map.panTo(marker.getPosition());
        });
        marker.setMap(map);
    
        // Add polyline
        var points = [ new google.maps.LatLng(39.8543, -73.2183), new google.maps.LatLng(41.705311, -75.2581939), new google.maps.LatLng(40.62388, -75.5483) ];
        var polyOptions =
        {
          path: points,
          strokeColor: '#FF0000',
          strokeOpacity: 1.0,
          strokeWeight: 2
        };
        historyPolyline = new google.maps.Polyline(polyOptions);
        historyPolyline.setMap(map);
    
        // Add polygon
        var points = [ new google.maps.LatLng(37.314166, -75.432),new google.maps.LatLng(40.2653, -74.4325), new google.maps.LatLng(38.8288, -76.5483) ];
          var polygon = new google.maps.Polygon(
        {
          paths: points,
          fillColor:  '#000000',
          fillOpacity: 0.2,
          strokeWeight: 3,
          strokeColor: '#fff000',
        });
        polygon.setMap(map);
    
        // Setup drawing manager
        var drawingManager = new google.maps.drawing.DrawingManager();
        drawingManager.setMap(map);
      }
    
      google.maps.event.addDomListener(window, 'load', initialize);
    
    </script>
  12. Once you're done with that, compile and run the project. You should see something similar to this:
    How to do it…

How it works…

Google allows you to embed Google Maps in a web page by 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 a HTML file to our web view 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.

Google allows your website to call any Google API, many thousands of times per day. If you plan for heavier traffic, you should get a free API key from Google. Go to https://console.developers.google.com to get a free key and replace the word 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 added 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 also 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. What it does is basically pan 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 the previous step.

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
3.148.144.228