在InfoWindow中嵌入地图

时间:2015-10-23 21:49:19

标签: javascript google-maps

我试图在InfoWindow中嵌入一个地图,以便创建一个带有预览聚类的弹出窗口。但是,一旦InfoWindow关闭,map div就无法呈现。

我尝试使用简化的jsfiddle,http://jsfiddle.net/behewur2/

function initialize() {
    var mapOptions = {
        center: {
            lat: -34.9290,
            lng: 138.6010
        },
        zoom: 8,
        streetViewControl: false,
        overviewMapControl: false
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    var mcOptions = {
        gridSize: 30,
        zoomOnClick: false
    };
    var mcOptionsZoom = {
        gridSize: 30,
        zoomOnClick: true
    };
    var mc = new MarkerClusterer(map, [], mcOptions);
    google.maps.event.addListener(mc, 'clusterclick',

    function (cluster) {
        if (typeof infowindow !== 'undefined') prevInfoWindow = infowindow;
        infowindow = new google.maps.InfoWindow({
            content: $('#inner-map-canvas')[0]
        });
        if (typeof prevInfoWindow !== 'undefined') prevInfoWindow.close();
        infowindow.setPosition(cluster.getCenter());
        infowindow.open(map);
        google.maps.event.trigger(innermap, 'resize');
        innermap.setZoom(innermap.getZoom());
        for (var i = 0; i < cluster.getMarkers().length; i++) {
            innermc.addMarker(
            new google.maps.Marker({
                position: cluster.getMarkers()[i].position,
                map: innermap,
                icon: cluster.getMarkers()[i].icon,
                title: cluster.getMarkers()[i].title
            }),
            false);
        }
    });
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(mapOptions.center.lat, mapOptions.center.lng),
        map: map,
        icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=0|FF0000|000000'
    });
    mc.addMarker(marker, false);
    var innermap = new google.maps.Map(document.getElementById("inner-map-canvas"), mapOptions);
    var innermc = new MarkerClusterer(innermap, [], mcOptionsZoom);
}
google.maps.event.addDomListener(window, 'load', initialize);

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDKxl8sh1TEN61taio3wdbGwuSI8FVeQ5k"></script>
<script type="text/javascript" src="https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer_packed.js"></script>
<div id="map-canvas"></div>
<div id="inner-map-canvas">
</dev>

1 个答案:

答案 0 :(得分:2)

最好在infowindow中动态创建div节点,当infowindow关闭时它会被销毁。

google.maps.event.addListener(mc, 'clusterclick', function (cluster) {
    if (typeof infowindow !== 'undefined') prevInfoWindow = infowindow;
    var innermapNode = document.createElement("div");
    innermapNode.setAttribute("id", "inner-map-canvas");
    innermapNode.style.height = "300px";
    innermapNode.style.width = "300px";
    infowindow = new google.maps.InfoWindow({
        content: innermapNode
    });
    if (typeof prevInfoWindow !== 'undefined') prevInfoWindow.close();
    infowindow.setPosition(cluster.getCenter());
    infowindow.open(map);
    innermap = new google.maps.Map(innermapNode, mapOptions);
    innermc = new MarkerClusterer(innermap, [], mcOptionsZoom);
    google.maps.event.addListener(infowindow, 'domready', function () {
        google.maps.event.trigger(innermap, 'resize');

        // innermap.setZoom(innermap.getZoom());
        var bounds = new google.maps.LatLngBounds();
        for (var i = 0; i < cluster.getMarkers().length; i++) {
            innermc.addMarker(
            new google.maps.Marker({
                position: cluster.getMarkers()[i].position,
                map: innermap,
                icon: cluster.getMarkers()[i].icon,
                title: cluster.getMarkers()[i].title,
                keycount: cluster.getMarkers()[i].keycount
            }),
            false);
            bounds.extend(cluster.getMarkers()[i].position);
        }
        google.maps.event.trigger(innermap, 'resize');
        innermap.fitBounds(bounds);
    });
});

proof of concept fiddle

代码段

&#13;
&#13;
function colorForCount(count) {
  if (count == 1) return '4080FE';
  if (count == 2) return 'F7C207';
  if (count > 2 && count < 5) return 'F50D07';
  if (count >= 5) return 'FF00F0';
  else return 'B600FF';
}
var innermap;
var innermc;

function initialize() {
  var mapOptions = {
    center: {
      lat: -34.9290,
      lng: 138.6010
    },
    zoom: 8,
    streetViewControl: false,
    overviewMapControl: false
  };
  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  var mcStyles = [{
    url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m1.png",
    height: 53,
    width: 53
  }, {
    url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m2.png",
    height: 53,
    width: 53
  }, {
    url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m3.png",
    height: 53,
    width: 53
  }, {
    url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m4.png",
    height: 53,
    width: 53
  }, {
    url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m5.png",
    height: 53,
    width: 53
  }];
  var mcOptions = {
    gridSize: 30,
    zoomOnClick: false,
    styles: mcStyles
  };
  var mcOptionsZoom = {
    gridSize: 30,
    zoomOnClick: true,
    styles: mcStyles
  };
  var mc = new MarkerClusterer(map, [], mcOptions);
  mc.setCalculator(function(markers, numStyles) {
    var count = markers.length;
    var total = 0;
    var max = 0;
    var index = 0;
    if (max == 1) index = 0;
    if (max == 2) index = 2;
    if (max > 2 && max < 5) index = 3;
    if (max >= 5) index = 4;
    return {
      text: count,
      index: index
    };
  });

  google.maps.event.addListener(mc, 'clusterclick',

    function(cluster) {
      if (typeof infowindow !== 'undefined') prevInfoWindow = infowindow;
      var innermapNode = document.createElement("div");
      innermapNode.setAttribute("id", "inner-map-canvas");
      innermapNode.style.height = "300px";
      innermapNode.style.width = "300px";
      infowindow = new google.maps.InfoWindow({
        content: innermapNode
      });
      if (typeof prevInfoWindow !== 'undefined') prevInfoWindow.close();
      infowindow.setPosition(cluster.getCenter());
      infowindow.open(map);
      innermap = new google.maps.Map(innermapNode, mapOptions);
      innermc = new MarkerClusterer(innermap, [], mcOptionsZoom);
      google.maps.event.addListener(infowindow, 'domready', function() {
        google.maps.event.trigger(innermap, 'resize');

        // innermap.setZoom(innermap.getZoom());
        var bounds = new google.maps.LatLngBounds();
        for (var i = 0; i < cluster.getMarkers().length; i++) {
          innermc.addMarker(
            new google.maps.Marker({
              position: cluster.getMarkers()[i].position,
              map: innermap,
              icon: cluster.getMarkers()[i].icon,
              title: cluster.getMarkers()[i].title,
              keycount: cluster.getMarkers()[i].keycount
            }),
            false);
          bounds.extend(cluster.getMarkers()[i].position);
        }
        google.maps.event.trigger(innermap, 'resize');
        innermap.fitBounds(bounds);
      });
    });

  google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
    var mapBnds = map.getBounds();
    var mapSpan = mapBnds.toSpan();
    for (var i = 0; i < 25; i++) {
      var latRan = (Math.random() * mapSpan.lat() / 2) + mapSpan.lat() / 4;
      var lngRan = (Math.random() * mapSpan.lng() / 2) + mapSpan.lng() / 4;
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(mapBnds.getSouthWest().lat() + latRan, mapBnds.getSouthWest().lng() + lngRan),
        map: map,
        icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + i + '|FF0000|000000'
      });
      mc.addMarker(marker, false);
    }
  });


}
google.maps.event.addDomListener(window, 'load', initialize);

/**
 * Pull out the unique keys and counts.
 * @param {Object} json The Inventory object.
 * @return {Array.<{portal:{portalGuid:string,portalLocation:string,
 *    portalImageUrl:string,portalTitle:string,portalAddress:string},
 *  count:number}>}
 */
function getKeys(json) {
  // parse the json string
  var inventory = json.gameBasket.inventory;

  // loop over the inventory items to find keys
  var keys = [];
  var iitckeys = {};
  for (var i = 0; i < inventory.length; i++) {
    // if it's a key, attempt to add to the key list
    var item = inventory[i];
    if (item[2].resource && item[2].resource.resourceType == "PORTAL_LINK_KEY") {
      addKey(keys, iitckeys, item[2].portalCoupler);
    } else if (item[2].resource && (item[2].resource.resourceType == "CAPSULE" || item[2].resource.resourceType == "INTEREST_CAPSULE")) {
      parseCapsule(keys, iitckeys, item[2].container.stackableItems);
    }
  }

  // return back the keys
  return {
    keys: keys,
    iitckeys: iitckeys
  };
}

/**
 * Parse the items within a capsule.
 * @param {Array.<{portal:{portalGuid:string,portalLocation:string,
 *    portalImageUrl:string,portalTitle:string,portalAddress:string},
 *  count:number}>} keys The current key array.
 * @param {Array.<Object>} items The capsule's contents.
 */
function parseCapsule(keys, iitckeys, items) {
  for (var i = 0; i < items.length; i++) {
    if (typeof items[i].exampleGameEntity[2].resource !== 'undefined') {
      if (items[i].exampleGameEntity[2].resource.resourceType == "PORTAL_LINK_KEY") {
        var count = items[i].itemGuids.length;
        while (count > 0) {
          addKey(keys, iitckeys, items[i].exampleGameEntity[2].portalCoupler);
          count--;
        }
      }
    }
  }
}

/**
 * Add a key def to the keys list.
 * @param {Array.<{portal:{portalGuid:string,portalLocation:string,
 *    portalImageUrl:string,portalTitle:string,portalAddress:string},
 *  count:number}>} keys The current key array.
 * @param {{portalGuid:string,portalLocation:string,portalImageUrl:string,
 *  portalTitle:string,portalAddress:string}} keyDef The key definition.
 */
function addKey(keys, iitckeys, keyDef) {
  // try to find the key and increment the count
  console.log("keyDef : " + keyDef);
  for (var i = 0; i < keys.length; i++) {
    if (keys[i].portal.portalGuid == keyDef.portalGuid) {
      keys[i].count++;
      iitckeys[keyDef.portalGuid] ++;
      return;
    }
  }

  // couldn't find the key, add it
  keys.push({
    portal: keyDef,
    count: 1
  });
  iitckeys[keyDef.portalGuid] = 1;
}

function getLatLng(location) {
  var newLoc = parseInt(location, 16);
  //if MSB is set
  if ((newLoc & 0x80000000) !== 0x00000000) {
    console.log("neg");
    return (newLoc - 0x100000000) / 1E6;
  } else {
    console.log("pos");
    return newLoc / 1E6;
  }
}
&#13;
body,
html {
  height: 100%;
  width: 100%;
}
#map-canvas {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
.cluster img {
  width: 53px;
  height: 53px;
}
#commands {
  width: 100%;
}
#inner-map-canvas {
  width: 300px;
  height: 300px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script>
<div id="map-canvas"></div>
<div id="keyjson"></div>
&#13;
&#13;
&#13;