Caspert
Caspert

Reputation: 4363

How to create multiple Google maps on the same page(not markers)?

I am searching for a solution for the following: I have one JSON file that consists out of multiple locations. Each location object contains of longitude, latitude and the location title.

What I would like to have is that for each JSON object, so for each location, there will be create a new Google Maps on the same page. Not hardcoded.

I use the very basic markup for displaying Google Maps. Live example you can see here: http://codepen.io/Caspert/pen/VvXXGP

{

    "title":    "Locations",

    "locations": [

        ,{

            "title":  "Location 1",

            "lat":  51.5046803,

            "lng": -0.1746135

        },{

            "title":  "Location 2",

            "lat":  51.5046403,

            "lng": -0.1744135

        },{

            "title":  "Location 3",

            "lat":  51.5046403,

            "lng": -0.1744135

        }

        ]

}

I read out my JSON file with jQuery AJAX, like the following:

init: function(){

    // Development
    console.log('init dataController');

    // Declare variables
    var root = this; // This in this function

    $.ajax({
        url: 'api/videoData.js',
        dataType: 'json',
        success: function(data) {

            root.dataArr = data;
            root.objectArr = root.dataArr.content;

            var modelCount = 0;
            var modelTypeCount = 0;


            // When all objects are received
            $.when(

                // Deferred object (probably Ajax request)
                // GET text format
                $.get('directives/format-text.html', function(response){
                    console.log('succes');
                    console.log(response);
                    root.dataModelText = response;
                }), 

                // GET location format
                $.get('directives/format-map.html', function(response){
                    console.log('succes');
                    console.log(response);
                    root.dataModelLocation = response;
                }), 

            )

            .then(function() {
                for (var i = 0; i < data.content.length; i++) {

                    if (data.content[modelCount].type == 'text' || data.content[modelCount].type == 'youtube' || data.content[modelCount].type == 'tickets') {
                        Triptube.dataController.getDataText(root.dataModelText, data, modelCount);
                    }

                    if (data.content[modelCount].type == 'location') {
                        modelTypeCount++;
                        Triptube.dataController.getDataLocation(root.dataModelLocation, data, modelCount, modelTypeCount);
                    }

                    modelCount++;

                }
            });


            function getData() {

                var modelParts = 4;
                var modelCount = 0;

                for (var i = 0; i < modelParts; i++) {

                    if (data.content[modelCount].type == 'location') {
                        console.log('type == location');
                    };

                    modelCount++;
                    console.log(modelCount);
                }

                $('body').removeClass('loading'); 

            } 

        },

        error: function(data) { 
            console.log(data);
            console.log('Houston, we have a problem!');
        }


    });


},

getDataLocation: function(dataModelLocation, data, modelCount, modelTypeCount){

    var root = this;

    var raw_model = root.dataModelLocation;
    model = $(raw_model);
    var dataID = data.content[modelCount].timeTrigger;
    var dataIndex = modelCount;

    model.attr('data-id', dataID);
    model.attr('data-index', dataIndex);

    model.find('.format').addClass(' ' + data.content[modelCount].type);
    model.find('#map').attr('map-id', modelTypeCount);

    $(model).insertBefore('.featured .footer');
}, 

I look out for an solution.

UPDATE

I came up with the following: http://codepen.io/Caspert/pen/LpdwZW?editors=101

With the instructions of @Nedvajz I get the following error on panning in the map:

Uncaught TypeError: Cannot read property 'x' of undefined

The map id's have it's unique index, but all the same google maps values:

enter image description here

Upvotes: 2

Views: 1920

Answers (3)

geocodezip
geocodezip

Reputation: 161404

  1. create a <div> to put the map in, append that to the body of the document

    var mapDiv = document.createElement("div");
    mapDiv.setAttribute("id", "map" + i);
    // mapDiv.style.height = "500px";
    // mapDiv.style.width = "500px";
    mapDiv.className = "map";
    var body = document.getElementsByTagName("body")[0];
    body.appendChild(mapDiv);
    
  2. create your map in the <div>, adding a marker at the center

    maps[i] = new google.maps.Map(mapDiv, mapOptions);
    var marker = new google.maps.Marker({
        position: {
            lat: mapJsonData.locations[i].lat,
            lng: mapJsonData.locations[i].lng
        },
        title: mapJsonData.locations[i].title,
        map: maps[i]
    });
    

proof of concept fiddle

code snippet:

function initMap() {

  var latlng = {
    lat: 51.5046803,
    lng: -0.1746135
  };

  var mapOptions = {
    center: latlng,
    scrollwheel: false,
    zoom: 12,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true
  };

  var maps = [];

  for (var i = 0; i < mapJsonData.locations.length; i++) {
    console.log(mapJsonData.locations[i]);
    mapOptions.center = {
      lat: mapJsonData.locations[i].lat,
      lng: mapJsonData.locations[i].lng
    };
    // Create map
    var mapDiv = document.createElement("div");
    mapDiv.setAttribute("id", "map" + i);
    // mapDiv.style.height = "500px";
    // mapDiv.style.width = "500px";
    mapDiv.className = "map";
    var body = document.getElementsByTagName("body")[0];
    body.appendChild(mapDiv);
    maps[i] = new google.maps.Map(mapDiv, mapOptions);
    var marker = new google.maps.Marker({
      position: {
        lat: mapJsonData.locations[i].lat,
        lng: mapJsonData.locations[i].lng
      },
      title: mapJsonData.locations[i].title,
      map: maps[i]
    });
  }
}
google.maps.event.addDomListener(window, "load", initMap);
var mapJsonData = {
  "title": "Locations",
  "locations": [{
    "title": "Location 1",
    "lat": 51.5046803,
    "lng": -0.1746135,
  }, {
    "title": "Location 2",
    "lat": 42.0,
    "lng": -72
  }, {
    "title": "Location 3",
    "lat": 35,
    "lng": -117
  }]
};
html,
body,
.map {
  height: 200px;
  width: 400px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>

Upvotes: 0

Nedvajz
Nedvajz

Reputation: 1029

You have to make for each item its own element & map object. It will let you assign the marker for each map then. Like so: http://codepen.io/anon/pen/epMqKz

With file you provided plese do something like:

function initMap() {
    var locations = [
        ['Bondi Beach', -33.890542, 151.274856, 4],
        ['Coogee Beach', -33.923036, 151.259052, 5],
        ['Cronulla Beach', -34.028249, 151.157507, 3],
        ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
        ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var maps = [];
    for (var i = 0; i < locations.length; i++) {
        console.log(locations[i][1]);
        $('.maps-wrapper').append('<div class="map" id="map' + i + '"></div>');

        var latlng = {lat: locations[i][1], lng: locations[i][2]};

        var mapOptions = {
           center: latlng,
           scrollwheel: false,
           zoom: 12,
           mapTypeId: google.maps.MapTypeId.ROADMAP,
           disableDefaultUI: true
       };

       var map = new google.maps.Map(document.getElementById('map' + i), mapOptions);
       maps.push(map);


       var marker = new google.maps.Marker({
          map: map,
          position: latlng,
          title: locations[i][0]
       });
    };
}

initMap();

Upvotes: 1

Mladen Oršolić
Mladen Oršolić

Reputation: 1422

Here is a modified code pen with 2 maps, you should be able to figure out how to further increase the number if needed

http://codepen.io/anon/pen/avYged

For the html part you need 2 or more divs to contain maps

<div id="map"></div>
<div id="map2"></div>

In your javascript u need to create 2 or more maps

// Create map
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var map2 = new google.maps.Map(document.getElementById('map2'), mapOptions);

And in your css you can apply separate styles if needed to each map

#map {
  height: 400px;
  width: 48%;
  display: block;
  float: left;
}

#map2 {
  height: 400px;
  width: 48%;
  display: block;
  float: left;
}

Upvotes: 0

Related Questions