Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 谷歌地图中的信息窗口在多个标记上_Javascript_Html_Google Maps_Csv - Fatal编程技术网

Javascript 谷歌地图中的信息窗口在多个标记上

Javascript 谷歌地图中的信息窗口在多个标记上,javascript,html,google-maps,csv,Javascript,Html,Google Maps,Csv,我创建了一个谷歌地图,它从csv文件中检索数据。这似乎很好,但是当我循环遍历所有对象时,infoWindow似乎不起作用。我想这是因为标记变量位于for循环内。我尝试将代码移动到循环内部,但是这会导致信息窗口随机放置在地图上,而不是单击标记的上方。如何使用多个标记实现infoWindow db.csv示例 40.740;-74.18;test;haha; 40.740;-74.20;test;haha; html和java <head> <link rel="styles

我创建了一个谷歌地图,它从csv文件中检索数据。这似乎很好,但是当我循环遍历所有对象时,infoWindow似乎不起作用。我想这是因为
标记
变量位于for循环内。我尝试将代码移动到循环内部,但是这会导致信息窗口随机放置在地图上,而不是单击标记的上方。如何使用多个标记实现infoWindow

db.csv示例

40.740;-74.18;test;haha;
40.740;-74.20;test;haha;
html和java

<head>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="normalize.css">

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>

<div id="mapContainer">

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

  <div id="abc">
    <div id="popupContact">
      <section class="register">
        <h1>CAMP INFORMATIONER:</h1>
        <form method="post" action="index.html">

          <div class="reg_section personal_info">
            <input type="text" name="username" value="" placeholder="Campnavn">
            <textarea name="textarea" id="description" placeholder="Beskrivelse"></textarea>
          </div>


          <div>
            <span class="submit" style="text-align: left; padding: 0 10px;"><input TYPE="button"name="commit" value="Tilføj" onclick="placeMarker(currentMarker, document.getElementById('description'));"></span>
            <span class="submit" style="text-align: right; padding: 0 10px;"><input TYPE="button" name="commit" value="Fortryd" onclick="div_hide();"></span>
          </div>

        </form>
      </section>

    </div>
  </div>
</div>




  <script>
  var mapCanvas;
  var currentMarker;
  function initialize() {

    var myOptions = {
      center: {lat: 40.740, lng: -74.18},
      zoom : 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    mapCanvas = new google.maps.Map(document.getElementById("mapContainer"), myOptions);

    var returnValue = "";
    var request = new XMLHttpRequest();

    // Read the lat/long info for markers
    request.open("GET", "db.csv", false);
    request.send(null);
    returnValue = request.responseText;

    // Convert our data from the CVS file to a usable array
    var data = CSVToArray(returnValue);

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

      // Create a lat/long object readable by Google
      var myLatlng = new google.maps.LatLng(parseFloat(data[i][0]), parseFloat(data[i][1]));

      // Generate a marker from the lat/long object and add it to the map
      var marker = new google.maps.Marker({
        position: myLatlng,
        map: mapCanvas,
        title: data[i][2],
        description: data[i][3]

      });



    }

    var imageBounds = {
      north: 40.773941,
      south: 40.712216,
      east: -74.12544,
      west: -74.22655
    };
    historicalOverlay = new google.maps.GroundOverlay(
    'http://i.stack.imgur.com/0mgx2.jpg',
    imageBounds);
    historicalOverlay.setMap(mapCanvas);

    // This event listener calls addMarker() when the map is clicked.
    google.maps.event.addListener(historicalOverlay, 'click', function(e) {
       console.log("clicked'");
       currentMarker = e.latLng;
       infowindow.close();
       div_show();

     });


    //Changes zoom levels when the projection is available.
    google.maps.event.addListenerOnce(mapCanvas, "projection_changed", function(){
      mapCanvas.setMapTypeId(google.maps.MapTypeId.HYBRID);  //Changes the MapTypeId in short time.
      setZoomLimit(mapCanvas, google.maps.MapTypeId.ROADMAP);
      setZoomLimit(mapCanvas, google.maps.MapTypeId.HYBRID);
      setZoomLimit(mapCanvas, google.maps.MapTypeId.SATELLITE);
      setZoomLimit(mapCanvas, google.maps.MapTypeId.TERRAIN);
      mapCanvas.setMapTypeId(google.maps.MapTypeId.ROADMAP);  //Sets the MapTypeId to original.
    });

    // InfoWindow content
var content = '<div id="iw-container">' +
                  '<div class="iw-title">title</div>' +
                  '<div class="iw-content">' +
                    '<p>Founded in 1824, the Porcelain Factory of Vista Alegre was the first industrial unit dedicated to porcelain production in Portugal. For the foundation and success of this risky industrial development was crucial the spirit of persistence of its founder, José Ferreira Pinto Basto. Leading figure in Portuguese society of the nineteenth century farm owner, daring dealer, wisely incorporated the liberal ideas of the century, having become "the first example of free enterprise" in Portugal.</p>' +
                  '</div>' +
                  '<div class="iw-bottom-gradient"></div>' +
                '</div>';

    // A new Info Window is created and set content
    var infowindow = new google.maps.InfoWindow({
      content: content,

      // Assign a maximum value for the width of the infowindow allows
      // greater control over the various content elements
      maxWidth: 350
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(mapCanvas, marker);

      //title
      document.getElementById("iw-title").innerHTML = marker.title;

      //description
      document.getElementById("iw-content p").innerHTML = marker.description;

    });

    // Event that closes the Info Window with a click on the map
    google.maps.event.addListener(mapCanvas, 'click', function() {
      infowindow.close();
    });

    google.maps.event.addListener(infowindow, 'domready', function() {

      // Reference to the DIV that wraps the bottom of infowindow
      var iwOuter = $('.gm-style-iw');

      /* Since this div is in a position prior to .gm-div style-iw.
       * We use jQuery and create a iwBackground variable,
       * and took advantage of the existing reference .gm-style-iw for the previous div with .prev().
      */
      var iwBackground = iwOuter.prev();

      // Removes background shadow DIV
      iwBackground.children(':nth-child(2)').css({'display' : 'none'});

      // Removes white background DIV
      iwBackground.children(':nth-child(4)').css({'display' : 'none'});

      // Moves the infowindow 115px to the right.
      iwOuter.parent().parent().css({left: '115px'});

      // Moves the shadow of the arrow 76px to the left margin.
      iwBackground.children(':nth-child(1)').attr('style', function(i,s){ return s + 'left: 76px !important;'});

      // Moves the arrow 76px to the left margin.
      iwBackground.children(':nth-child(3)').attr('style', function(i,s){ return s + 'left: 76px !important;'});

      // Changes the desired tail shadow color.
      iwBackground.children(':nth-child(3)').find('div').children().css({'z-index' : '1'});

      // Reference to the div that groups the close button elements.
      var iwCloseBtn = iwOuter.next();

      // Apply the desired effect to the close button
      iwCloseBtn.css({opacity: '1', right: '38px', top: '3px', border: '7px solid #fff', 'border-radius': '13px', 'box-shadow': '0 0 5px #7D0F33'});

      // If the content of infowindow not exceed the set maximum height, then the gradient is removed.
      if($('.iw-content').height() < 140){
        $('.iw-bottom-gradient').css({display: 'none'});
      }

      // The API automatically applies 0.7 opacity to the button after the mouseout event. This function reverses this event to the desired value.
      iwCloseBtn.mouseout(function(){
        $(this).css({opacity: '1'});
      });
    });


}
function div_show() {
  $('#abc').fadeIn(400);

}
//Function to Hide Popup
function div_hide(){
  $('#abc').fadeOut(400);
}
  function placeMarker(location, label) {
    var marker = new google.maps.Marker({
        position: location,
        map: mapCanvas,
        labelContent : label
    });
    div_hide();
  }

  function setZoomLimit(map, mapTypeId){
    //Gets MapTypeRegistry
    var mapTypeRegistry = map.mapTypes;

    //Gets the specified MapType
    var mapType = mapTypeRegistry.get(mapTypeId);
    //Sets limits to MapType
    mapType.maxZoom = 15;  //It doesn't work with SATELLITE and HYBRID maptypes.
    mapType.minZoom = 15;
  }

  function CSVToArray(strData, strDelimiter ){
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = (strDelimiter || ";");

    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp(
        (
            // Delimiters.
            "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

            // Quoted fields.
            "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

            // Standard fields.
            "([^\"\\" + strDelimiter + "\\r\\n]*))"
        ), "gi");

    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [[]];

    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;

    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec( strData ))
    {
        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[ 1 ];

        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter))
        {
            // Since we have reached a new row of data,
            // add an empty row to our data array.
            arrData.push( [] );

        }

        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[ 2 ]){
            // We found a quoted value. When we capture
            // this value, unescape any double quotes.
            var strMatchedValue = arrMatches[ 2 ].replace(
                new RegExp( "\"\"", "g" ),
                "\""
                );

        } else
        {
            // We found a non-quoted value.
            var strMatchedValue = arrMatches[ 3 ];
        }

        // Now that we have our value string, let's add
        // it to the data array.
        arrData[ arrData.length - 1 ].push( strMatchedValue );
    }

    // Return the parsed data.
    return( arrData );
}

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



    </script>
    <body>

我认为应该将标记对象存储在对象数组中。例:

var arrayOfMarkers = [];
for (var i = 0; i < data.length; i++) {
      // Create a lat/long object readable by Google
      var myLatlng = new google.maps.LatLng(parseFloat(data[i][0]), parseFloat(data[i][1]));
      // Generate a marker from the lat/long object and add it to the map
      var marker = new google.maps.Marker({
        position: myLatlng,
        map: mapCanvas,
        title: data[i][2],
        description: data[i][3]
      });
      arrayOfMarkers.push(marker);
  }
然后调用
google.maps.event.addListener(marker,…)


这一行怎么办?
google.maps.event.addListener(marker,'click',function(){
我想这应该更改为,因为它无法访问marker?是的,您可能需要通过为
event.addListener
添加循环来迭代每个标记,所以它可能看起来像
google.maps.event.addListener(arrayOfMarkers[i] ,'click',function(){
hmm信息窗口似乎仍然没有显示。我想我需要更改
infoWindow.open(mapCanvas,marker);
infoWindow.open(mapCanvas,arrayOfMarkers[i])
但是仍然不起作用,我想你也需要为每个标记创建一个infowindows对象,我找到了这个关于多个标记和infowindows的参考,也许这会有帮助嗨,我也试着提供了一个示例,希望能有所帮助
var arrayOfMarkers = [];
for (var i = 0; i < data.length; i++) {
      // Create a lat/long object readable by Google
      var myLatlng = new google.maps.LatLng(parseFloat(data[i][0]), parseFloat(data[i][1]));
      // Generate a marker from the lat/long object and add it to the map
      var marker = new google.maps.Marker({
        position: myLatlng,
        map: mapCanvas,
        title: data[i][2],
        description: data[i][3]
      });
      arrayOfMarkers.push(marker);
  }
this.instance = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(40.740, -74.18),
    zoom: 13,
});

this.addGroundOverlay = function(data) {
    var instance = this.instance;
    var groundOverlay = new google.maps.GroundOverlay(
    'http://i.stack.imgur.com/0mgx2.jpg',data);
    groundOverlay.setMap(instance);
}
this.addMarker = function(data) {
    var Map = this;
    var instance = this.instance;
    var content = String.format(this.contentTemplate, data.image_url, data.name, data.summary);
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(data.latitude, data.longitude),
      title: data.name
    });
    marker.setMap(instance);
    google.maps.event.addListener(marker, 'click', function() {
      var imageBound = {
          north: 40.773941,
          south: 40.712216,
          east: -74.12544,
          west: -74.22655
      } 
      Map.addGroundOverlay(imageBound);
    });
}