Google Maps JavaScript API - Arranging Layers

I am facing an issue with my map setup where the building footprints from GeoJSON are being overlapped by Street View geometries. When using Google Maps and dragging Pegman to access Street View, the geometries on my map appear above those of Street View.

I am looking for a solution to place the Street View layer above the Data layer (containing GeoJSON shapes) so that street, path, and 360 geometries from Street View are displayed visibly above the GeoJSON building footprint geometries.

Despite extensive research through Google Maps JavaScript API documentation and multiple searches online, I have not been able to find a method to re-order layers similar to how it can be done with OpenLayers and Leaflet.

The issue is illustrated in the provided screenshot where a path and a 360 panorama are partially covered by the GeoJSON geometry.

https://i.sstatic.net/YDhc9.png

Answer №1

@Dr.Molle shared an example of overlaying two maps in a similar inquiry: How to put Google Map labels on top?

If you follow that approach and place the GeoJSON data on the lower map, the StreetView layer will display on top of the GeoJSON.

  let map = new google.maps.Map(document.getElementById("map"), {
    zoom: 16,
    center: {
      lat: 40.7127753,
      lng: -74.0159728
    },
  });
  let map2 = new google.maps.Map(document.getElementById('map2'), {
    mapTypeControl: false,
    backgroundColor: 'hsla(0, 0%, 0%, 0)',
    zoom: map.getZoom(),
    styles: [{
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "elementType": "labels",
      "stylers": [{
        "visibility": "on"
      }]
    }],
    center: map.getCenter(),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  map.bindTo('center', map2, 'center');
  map.bindTo('zoom', map2, 'zoom');

CSS:

.map {
        width: 100%;
        height: 100%; 
        background:transparent !important;
    }

See proof of concept fiddle here

https://i.sstatic.net/lxVkx.png

code snippet:

function initMap() {
  let map = new google.maps.Map(document.getElementById("map"), {
    zoom: 16,
    center: {
      lat: 40.7127753,
      lng: -74.0159728
    },
  });
  let map2 = new google.maps.Map(document.getElementById('map2'), {
    mapTypeControl: false,
    backgroundColor: 'hsla(0, 0%, 0%, 0)',
    zoom: map.getZoom(),
    styles: [{
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "elementType": "labels",
      "stylers": [{
        "visibility": "on"
      }]
    }],
    center: map.getCenter(),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  map.bindTo('center', map2, 'center');
  map.bindTo('zoom', map2, 'zoom');
  // Load GeoJSON.
  map.data.addGeoJson(JSON.parse(geoJson));
  // Set the stroke width, and fill color for each polygon
  map.data.setStyle({
    fillColor: "green",
    fillOpacity: 1.0,
    strokeWeight: 1,
  });
}
var geoJson = '{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-74.01384776566772,40.71283222634755],[-74.01206677888183,40.71205151790942],[-74.0127105090454,40.71019729868139],[-74.01331132386474,40.71035995155685],[-74.01365464661865,40.71009970676538],[-74.01442712281494,40.71037621682256],[-74.01384776566772,40.71283222634755]]]},"properties":{}},{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-74.01672381852416,40.71865472137034],[-74.01286143754271,40.718248139094314],[-74.01485700104979,40.71120574010474],[-74.01661653016356,40.711953928711026],[-74.01631612275389,40.71348280971995],[-74.0174533793762,40.71362919010266],[-74.01672381852416,40.71865472137034]]]},"properties":{}}]}'
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.map {
  width: 100%;
  height: 100%;
  background: transparent !important;
}
<!DOCTYPE html>
<html>

<head>
  <title>Data Layer: Styling</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map" class="map"></div>
  <div id="map2" class="map" style="top:-100%;"></div>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js throws an error with the message "Unexpected token *" while utilizing the robe

Currently, I'm working on a Node.js application where I'm attempting to utilize the node module named robe. Unfortunately, I encountered an error message when trying to launch the app: function* promiseToGenerator(promise) { ^ Error l ...

When the input field is in debug mode and has a keydown event listener, the character fails to appear as intended

As a newcomer to javascript/html, I have an input with a keydown event listener. Surprisingly, everything seems to work fine when I try it out in the browser. I type a character and see that my javascript is executed, then I type another character and it w ...

Issue with Angular: boolean value remains unchanged

Currently, I'm encountering an issue with my application. My objective is to establish a list containing checkboxes that toggle their values between true and false when clicked. Sounds simple enough, right? Below is the HTML code snippet: <l ...

React's onDragStart event listener returns empty values

Having an issue with setting up a drag and drop feature in React. When using the "onDragStart" listener, the "event" outputs null values. dragStart(event) { // Getting null values for various fields here console.log(event); // NULL VALUES ev ...

Clicking on another function - JavaScript

I'm looking for a way to capture the onclick function of a div and trigger it when the backKey is pressed. Any help would be greatly appreciated! document.addEventListener("keydown", keyDownTextField, false); function keyDownTextField(e) { var k ...

Facilitate parent directory navigation

Hello everyone! I am currently developing an express application. At the top of my express file, I added this line to serve all static files from my working directory: app.use(express.static(__dirname)); Now, I am trying to send a file that is located in ...

Constructing a table in React using columns instead of the traditional rows

Currently tackling a project in react, I am looking to construct a material-ui table with specific characteristics. Within my array of elements, each element represents a column in the table and contains a name and the number of cells it covers. For examp ...

Tips on organizing a JSON object for a JavaScript project

For my project, I am designing a data structure that utilizes JSON. My goal is to create an efficient method for searching and editing the JSON object. Which structure would be considered standard in this scenario? Is there a preferred way to implement eit ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

Mapping with groups in JavaScript

Is there a way to create a mapping in JavaScript? Currently, I am able to do if (number < 32) { group = 1; else if (number < 72) { group = 2; } else if (number < 100) { group = 3; } else { group = -1; } Instead of this, I am interested ...

Building an AngularJS web application with a web.js architecture for seamless deployment on Heroku platform

I've been grappling with this deployment issue for weeks, without any luck. To run my app locally, I usually execute grunt serve and node backend/app.js. However, I'm trying to replicate the deployment setup used in this example. I also attempted ...

Tracking user sessions using cookies, not relying on JavaScript like Google does

Currently, I am working in an environment that utilizes PHP on the server side and Javascript on the client side. In order to monitor user sessions, I regularly send a JS PUT request to the server every 5 seconds. This allows me to gather data such as the ...

Implementing the migration of a route DTO object in NestJS

Utilizing NestJS for my application, there have been some modifications to the DTO objects that need to be received in the controller. Since the client side consists of a mobile app and users cannot be compelled to update their version, I may receive DTO o ...

Is there a way to access a JavaScript object using Perl?

Looking to manipulate a JavaScript Object file with 5.5mb of longitude latitude data? Consider opening it in Perl for applying a detail-reducing algorithm that will generate a new object file with reduced dataset. My approach involves using a for loop to s ...

Unexpected behavior observed when trying to smoothly scroll to internal links within a div, indicating a potential problem related to CSS dimensions and

Within a series of nested div containers, I have one with the CSS property overflow:hidden. My goal is to smoothly scroll to internal links within this specific div using jQuery. The snippet of code below has worked successfully in previous projects: ...

rails/jquery/ajax: The completion function is not being triggered

My code was functioning correctly without any errors when making an AJAX call that didn't require a return value. In my Javascript (specifically coffeescript), I had the following: $.ajax({ url: "/images/" + image_id + "/" + action, type ...

Having trouble submitting the form in ReactJs and Node.js

I have recently started learning ReactJs and NodeJs for the first time. My app includes a backend created with NodeJs and Express, and frontend in ReactJs. The server is functioning correctly, with all endpoints tested using Postman. I am currently workin ...

The useMutation method in react-query fails to reflect the latest updates on the user interface

I have a React 18 application that utilizes @tanstack/react-query version 5 for managing state. Currently, I am facing two issues. Firstly, upon clicking the like button, the UI does not reflect any changes. The expected behavior is for the number of like ...

Bokeh is having trouble loading from the CDN

I am currently attempting to embed a plot along with its data by utilizing autoload_static within a straightforward html page that I wish to view locally on my computer. According to the documentation, all I need to do is place the .js file in the specifie ...

The process of returning parameters from a modal view in Ionic

I am currently facing an issue with my modal view that is used for user login. I need to retrieve the user id from the modal and pass it back to the view behind. I attempted using $state.go but it was unsuccessful. Additionally, using ng-href would not wor ...