Integrating dual Google Maps onto a single HTML page

I'm facing an issue with implementing two Google maps on a single page where the second map seems to be malfunctioning.

Below is the code I am currently using:


<style>
#map-london {
    width: 500px;
    height: 400px;
}
#map-belgium {
    width: 500px;
    height: 400px;
}
</style>

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

<script>
    function initialize() {
      var myLatlng = new google.maps.LatLng(51.518865,-0.133108);
      var mapOptions = {
        zoom: 17,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById('map-london'), mapOptions);

      var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          title: 'Incopro London'
      });
    }

    google.maps.event.addDomListener(window, 'load', initialize);
</script>

<script>
    function initializeB() {
      var myLatlngBel = new google.maps.LatLng(50.802138,-1.07839);
      var mapOptionsBel = {
        zoom: 17,
        center: myLatlngBel,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var mapB = new google.maps.Map(document.getElementById('map-belgium'), mapOptionsBel);

      var markerB = new google.maps.Marker({
          position: myLatlngBel,
          map: mapB,
          title: 'Incopro Belgium'
      });
    }

    google.maps.event.addDomListener(window, 'load', initializeB);
</script>

To display the maps, I have utilized two div elements:

<div id="map-london"></div>
<div id="map-belgium"></div>

If anyone has any insights on how this can be resolved, please provide your input.

Thank you in advance.

Answer №1

Consider consolidating all the code into a single initialization function:

<script>
    function setupMaps() {
      var londonCoords = new google.maps.LatLng(51.518865,-0.133108);
      var belgiumCoords = new google.maps.LatLng(50.802138,-1.07839);

      var mapOptionsLondon = {
        zoom: 17,
        center: londonCoords,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var mapOptionsBelgium = {
        zoom: 17,
        center: belgiumCoords,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }

      var londonMap = new google.maps.Map(document.getElementById('map-london'), mapOptionsLondon);
      var belgiumMap = new google.maps.Map(document.getElementById('map-belgium'), mapOptionsBelgium);

      var londonMarker = new google.maps.Marker({
          position: londonCoords,
          map: londonMap,
          title: 'Incopro London'
      });
      var belgiumMarker = new google.maps.Marker({
          position: belgiumCoords,
          map: belgiumMap,
          title: 'Incopro Belgium'
      });
    }    
    google.maps.event.addDomListener(window, 'load', setupMaps);
</script>

Answer №2

Check out the JS Fiddle link below for a demonstration:

http://jsfiddle.net/89hv75h1/1/

    <!-- Sample Map -->
       <div id="map-canvas" style="width:100%; height:333px"></div>
         <br/><hr/>
       <!-- Another Map -->
       <div id="map-canvas_2" style="width:100%; height:333px"></div>
<script>
     function initialize() {
          var myLatlng = new google.maps.LatLng(25.18694, 55.2609596);
          var myLatlngBel = new google.maps.LatLng(25.18694, 55.2609596);

          var mapOptions = {
            zoom: 17,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          }

          var mapOptionsBel = {
            zoom: 17,
            center: myLatlngBel,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          }

          var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
          var mapB = new google.maps.Map(document.getElementById('map-canvas_2'), mapOptionsBel);

          marker = new google.maps.Marker({
        map:map,
        draggable:false,
        animation: google.maps.Animation.BOUNCE,
        position: myLatlng,
          icon: "http://oi62.tinypic.com/6fxyx5.jpg"
      });

          markerB = new google.maps.Marker({
            map:mapB,
            draggable:false,
            animation: google.maps.Animation.BOUNCE,
            position: myLatlngBel,
             icon: "http://oi62.tinypic.com/6fxyx5.jpg"
          });
            marker.setAnimation(google.maps.Animation.BOUNCE);
            markerB.setAnimation(google.mapB.Animation.BOUNCE);
        }   
        google.maps.event.addDomListener(window, 'load', initialize);


    $(document).ready(function() {

            initialize();

    });
</script>

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

Leveraging Emotion API in Video Content (JavaScript or Ruby)

Currently, I'm in the process of uploading a video to the Emotion API for videos, but unfortunately, I have not received any response yet. I managed to successfully upload it using the Microsoft online console. However, my attempts to integrate it in ...

An issue occurred while using AJAX in jQuery: there was an error converting a circular structure

After consoling JSON.stringify(stateArr), my JSON appears to be correct: { "shipping_options": [{ "id": "1", "name": "Kuala Lumpur", "rate": "222" }, { "id": "2", "name": "Labuan", "rate": "1" }] ...

Choosing the fourth cell in every row of a table and converting the information

Currently, I am working on a function that is supposed to take the fourth column in each row of a specific table, manipulate the data using a function, and return different data for the cell. This function takes an integer representing total minutes as i ...

How can you target the current component and use createElement within VueJS?

My goal is to gain access to the current component and generate a div within it once the component is ready. The following is the code snippet for my component, which demonstrates my attempt to target the this element and create a new div within it using ...

What is preventing me from being able to spyOn() specific functions within an injected service?

Currently, I am in the process of testing a component that involves calling multiple services. To simulate fake function calls, I have been injecting services and utilizing spyOn(). However, I encountered an issue where calling a specific function on one ...

Simple JavaScript numeric input field

Hey there, I'm a beginner learning JavaScript. I'm currently working on creating a program that adds numbers input through text fields. If you want to check out the HTML code, visit this link on JS Fiddle: http://jsfiddle.net/fCXMt/ My questio ...

Looking to modify the HTML layout in order to be compatible with a specific script

Utilizing a form validation script with required:true data-validation will stop the form from submitting and highlight invalid fields in red by adding "has-error" to the parent container when the user submits the form. In the code snippet below, "has-erro ...

Executing several GET requests in JavaScript

Is there a more efficient way to make multiple get requests to 4 different PHP files within my project and wait for all of them to return successfully before appending the results to the table? I have tried nesting the requests, but I'm looking for a ...

A method for consolidating multiple enum declarations in a single TypeScript file and exporting them under a single statement to avoid direct exposure of individual enums

I am looking to consolidate multiple enums in a single file and export them under one export statement. Then, when I import this unified file in another file, I should be able to access any specific enum as needed. My current setup involves having 2 separ ...

Adjusting the visible options in ngOptions causes a disruption in the selected value of the dropdown menu

I have successfully implemented a feature that allows users to convert temperature values displayed in a drop-down menu to either Celsius or Fahrenheit. For this functionality, I am using a select input with ng-options as shown below: <select ng-model ...

Coding with a combination of JavaScript, AngularJS, and manipulating brackets

I am currently performing the following action: myArray.push(pageCount); After that, I end up with something like this: $scope.myArray = Pages.getAllPageCount(); Finally, when I utilize AngularJS to display it in my .html file. {{myArray}} If there i ...

Adding a task to my database successfully through Postman integration

I'm having trouble implementing the code for my todo app using React. I am encountering an issue with adding a new todo to the database using the handleSubmit function. Oddly enough, it works fine when testing with Postman, but not when trying to inpu ...

Tips for generating JavaScript within list elements using a PHP script

My PHP script is designed to fetch data from a database and display it as list items within a jQuery Dialog. The process involves creating an array in the PHP while loop that handles the query results, with each list item containing data, an HTML button, a ...

When setting an attribute on load, Javascript may not properly apply the change to the attribute

I designed a webpage where images have a fade-in effect using a CSS class. Initially, 4 images load with the desired effect. However, I encounter an issue when trying to apply the same effect to a new image that appears upon clicking a button. Below is th ...

Tips for creating dynamic alerts using mui v5 Snackbar

My goal is to call an API and perform several actions. After each action, I want to display the response in a Snackbar or alert. Despite iterating through the messages in a map, I'm only able to show the first response and none of the others. Here is ...

Having difficulty removing new or existing lines on StackBlitz

I attempted to experiment with React on StackBlitz, but I encountered a problem where I couldn't delete any lines of code. It seems that while I can add new lines of code, deleting them is not an option. Even when logging in with GitHub, the issue per ...

Accessing audio files in a directory using ajax

I need assistance with implementing a feature in my mp3 music player code. I want the player to fetch songs from a directory instead of using the page's URL. var songs = [{ { title: 'Blackout City', artist: 'Anamanaguchi&ap ...

Detecting Changes in Angular2 Component Attributes via Observables

When working with Angular 2 components that have input attributes defined using @Input, how can I create an observable to track changes to those input attributes (not to be confused with user input from a form)? export class ExampleComponent implement OnC ...

What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format: Healthcare -- Insights driven by data for improved healthcare -- Urban Analytics Transport -- Urban Analytics Cities -- Urban Analytics I have attempted ...

Tips on concealing all elements besides the one with the ID of "mainContainer"

Efforts have been made to conceal everything except the main content on this particular Facebook post The following CSS code has been attempted without success - I would appreciate any assistance. html body * { display:none; } #contentArea { display:b ...