地图画布不会出现

时间:2015-05-28 12:03:22

标签: javascript html css google-maps canvas

我无法弄清楚我的错误..请帮助我 在我添加列表div之前,地图画布仍然显示,但之后我不再,我甚至尝试删除它并再次放置甚至更改高度和宽度..我无法看到问题请帮助我

继承我的CSS代码

html {
     background:linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)),url(superb-seaside-restaurant-hd-wallpaper-506329.jpg) no-repeat center center fixed;
    -webkit-background-size:cover;
    -moz-background-size:cover;
    background-size:cover;
    background-size:cover
}

#form{
    font:20px "Walkway SemiBold";
    letter-spacing:5px;
    text-align:center;
    padding:3px;
    padding-top:3px;
    width:50%;
    background:#ccc;
    margin-bottom: 10px;
/* Fallback for older browsers without RGBA-support */
    background:rgba(204,204,204,0.5);
    float:left;
}

#header {
    font:20px "Josefin Slab";
    letter-spacing:10px;
    background-color:#fff;
    color:#000;
    text-align:center;
    padding:3px;
    width:1255px;
    background:#ccc;
    margin-bottom: 10px;
/* Fallback for older browsers without RGBA-support */
    background:rgba(204,204,204,0.5);
}
 #map-canvas {
    -webkit-box-shadow:0 0 10px #bfdeff;
    -moz-box-shadow:0 0 5px #bfdeff;
    box-shadow:0 0 7px #bfdeff;
    float:right;
    height:100%;
    width:100%;
    padding:10px;
    margin-right:3px;
    vertical-align:top;
}
#listing {
    font:18pt "Nilland";
    letter-spacing:5px;
    text-align:center;
    padding:3px;
    height:40%;
    width:50%;
    background:#ccc;
    margin-bottom: 10px;
/* Fallback for older browsers without RGBA-support */
    background:rgba(204,204,204,0.5);
    float:left;
    }
#footer {
    font:20px "DistrictPro-Thin";
    letter-spacing:10px;
    background-color:#fff;
    color:#000;
    text-align:center;
    padding:3px;
    width:1255px;
    background:#ccc;
    margin-top: 10px;
/* Fallback for older browsers without RGBA-support */
    background:rgba(204,204,204,0.5);
    float:left;
}
    .placeIcon {
  width: 32px;
  height: 37px;
  margin: 4px;
}
.hotelIcon {
  width: 24px;
  height: 24px;
}
#resultsTable {
    font:16pt "Nilland-Black";
  border-collapse: collapse;
  width: 450px;
  margin-left:90px;
  float:left;
   background:rgba(204,204,204,0.5);
}
#rating {
  font-size: 13px;
  font-family: Arial Unicode MS;
}
#keywordsLabel {
  text-align: right;
  width: 70px;
  font-size: 14px;
  padding: 4px;
  position: absolute;
}
.iw_table_row {
  height: 18px;
}
.iw_attribute_name {
  font-weight: bold;
  text-align: right;
}

继承我的HTML代码

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Map</title>
<link href="sanamagwork.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">

  var map, places, iw;
  var markers = [];
  var searchTimeout;
  var centerMarker;
  var autocomplete;
  var hostnameRegexp = new RegExp('^https?://.+?/');

  function initialize() {
    var myLatlng = new google.maps.LatLng(37.786906,-122.410156);
    var myOptions = {
      zoom: 15,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
    places = new google.maps.places.PlacesService(map);
    google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);

    document.getElementById('keyword').onkeyup = function(e) {
      if (!e) var e = window.event;
      if (e.keyCode != 13) return;
      document.getElementById('keyword').blur();
      search(document.getElementById('keyword').value);
    }

    var typeSelect = document.getElementById('type');
    typeSelect.onchange = function() {
      search();
    };

    var rankBySelect = document.getElementById('rankBy');
    rankBySelect.onchange = function() {
      search();
    };

  }

  function tilesLoaded() {
    search();
    google.maps.event.clearListeners(map, 'tilesloaded');
    google.maps.event.addListener(map, 'zoom_changed', searchIfRankByProminence);
    google.maps.event.addListener(map, 'dragend', search);
  }

  function searchIfRankByProminence() {
    if (document.getElementById('rankBy').value == 'prominence') {
      search();
    }    
  }

  function search() {
    clearResults();
    clearMarkers();

    if (searchTimeout) {
      window.clearTimeout(searchTimeout);
    }
    searchTimeout = window.setTimeout(reallyDoSearch, 500);
  }

  function reallyDoSearch() {      
    var type = document.getElementById('type').value;
    var keyword = document.getElementById('keyword').value;
    var rankBy = document.getElementById('rankBy').value;

    var search = {};

    if (keyword) {
      search.keyword = keyword;
    }

    if (type != 'establishment') {
      search.types = [type];
    }

    if (rankBy == 'distance' && (search.types || search.keyword)) {
      search.rankBy = google.maps.places.RankBy.DISTANCE;
      search.location = map.getCenter();
      centerMarker = new google.maps.Marker({
        position: search.location,
        animation: google.maps.Animation.DROP,
        map: map
      });
    } else {
      search.bounds = map.getBounds();
    }

    places.search(search, function(results, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
          var icon = 'number_' + (i+1) + '.png';
          markers.push(new google.maps.Marker({
            position: results[i].geometry.location,
            animation: google.maps.Animation.DROP,
            icon: icon
          }));
          google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
          window.setTimeout(dropMarker(i), i * 100);
          addResult(results[i], i);
        }
      }
    });
  }

  function clearMarkers() {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
    }
    markers = [];
    if (centerMarker) {
      centerMarker.setMap(null);
    }
  }

  function dropMarker(i) {
    return function() {
      if (markers[i]) {
        markers[i].setMap(map);
      }
    }
  }

  function addResult(result, i) {
    var results = document.getElementById('results');
    var tr = document.createElement('tr');
    tr.style.backgroundColor = (i% 2 == 0 ? '#F0F0F0' : '#FFFFFF');
    tr.onclick = function() {
      google.maps.event.trigger(markers[i], 'click');
    };

    var iconTd = document.createElement('td');
    var nameTd = document.createElement('td');
    var icon = document.createElement('img');
    icon.src = 'number_' + (i+1) + '.png';
    icon.setAttribute('class', 'placeIcon');
    icon.setAttribute('className', 'placeIcon');
    var name = document.createTextNode(result.name);
    iconTd.appendChild(icon);
    nameTd.appendChild(name);
    tr.appendChild(iconTd);
    tr.appendChild(nameTd);
    results.appendChild(tr);
  }

  function clearResults() {
    var results = document.getElementById('results');
    while (results.childNodes[0]) {
      results.removeChild(results.childNodes[0]);
    }
  }

  function getDetails(result, i) {
    return function() {
      places.getDetails({
          reference: result.reference
      }, showInfoWindow(i));
    }
  }

  function showInfoWindow(i) {
    return function(place, status) {
      if (iw) {
        iw.close();
        iw = null;
      }

      if (status == google.maps.places.PlacesServiceStatus.OK) {
        iw = new google.maps.InfoWindow({
          content: getIWContent(place)
        });
        iw.open(map, markers[i]);        
      }
    }
  }

  function getIWContent(place) {
    var content = '';
    content += '<table>';
    content += '<tr class="iw_table_row">';
    content += '<td style="text-align: left"><img class="hotelIcon" src="' + place.icon + '"/></td>';
    content += '<td><b><a href="' + place.url + '">' + place.name + '</a></b></td></tr>';
    content += '<tr class="iw_table_row"><td class="iw_attribute_name">Address:</td><td>' + place.vicinity + '</td></tr>';
    if (place.formatted_phone_number) {
      content += '<tr class="iw_table_row"><td class="iw_attribute_name">Telephone:</td><td>' + place.formatted_phone_number + '</td></tr>';      
    }
    if (place.rating) {
      var ratingHtml = '';
      for (var i = 0; i < 5; i++) {
        if (place.rating < (i + 0.5)) {
          ratingHtml += '&#10025;';
        } else {
          ratingHtml += '&#10029;';
        }
      }
      content += '<tr class="iw_table_row"><td class="iw_attribute_name">Rating:</td><td><span id="rating">' + ratingHtml + '</span></td></tr>';
    }
    if (place.website) {
      var fullUrl = place.website;
      var website = hostnameRegexp.exec(place.website);
      if (website == null) { 
        website = 'http://' + place.website + '/';
        fullUrl = website;
      }
      content += '<tr class="iw_table_row"><td class="iw_attribute_name">Website:</td><td><a href="' + fullUrl + '">' + website + '</a></td></tr>';
    }
    content += '</table>';
    return content;
  }

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

</script>
<script>
//<![CDATA[
    function initialize() {
    var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
    var mapOptions = {
    zoom: 4,
    center: myLatlng
    }
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
    });
    }
    google.maps.event.addDomListener(window, 'load', initialize);
    //]]>
    </script>
</head>
<body>
 <div id="header">
      <h1>
        HEADER
      </h1>
    </div>
<div id="listing">
    Keywords:
    <input id="keyword" type="text" value="Mexican,Italian,Chinese..." />
  <div id="controls">
    <span id="typeLabel">
      Type:
    </span>
    <select id="type">
      <option value="bar">Bars</option>
      <option value="cafe">Cafe</option>
      <option value="restaurant" selected="selected">Restaurants</option>
      </select>
    <span id="rankByLabel">
      Rank by:
    </span>
    <select id="rankBy">
      <option value="prominence">Prominence</option>
      <option value="distance" selected="selected">Distance</option>
    </select>
  </div>
  </div>

  <div id="map_canvas"></div>

  <div id="listing" style="overflow-y: scroll; height:400px;"><table id="resultsTable"><tbody id="results"></tbody></table></div>

 <div id="footer">
        Credits to Google Maps and <a href=
        "http://mapicons.nicolasmollet.com">Maps Icons Collection</a>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

您的代码中有两个“Initialise”方法实例。 一个在顶部,一个在第二组脚本标签中,由CDATA标签包围。 第二个函数抛出一个错误,导致JS停止运行。

我拿出了第二种方法,然后我加载了地图画布(尽管它的大小和宽度都设置为零)。 这是因为您在map_canvas的HTML中的ID与css(map-canvas)中的ID不匹配

下面是一个固定的CSS:

html {
     background:linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)),url(superb-seaside-restaurant-hd-wallpaper-506329.jpg) no-repeat center center fixed;
    -webkit-background-size:cover;
    -moz-background-size:cover;
    background-size:cover;
    background-size:cover
}

    #form{
        font:20px "Walkway SemiBold";
        letter-spacing:5px;
        text-align:center;
        padding:3px;
        padding-top:3px;
        width:50%;
        background:#ccc;
        margin-bottom: 10px;
    /* Fallback for older browsers without RGBA-support */
        background:rgba(204,204,204,0.5);
        float:left;
    }

    #header {
        font:20px "Josefin Slab";
        letter-spacing:10px;
        background-color:#fff;
        color:#000;
        text-align:center;
        padding:3px;
        width:1255px;
        background:#ccc;
        margin-bottom: 10px;
    /* Fallback for older browsers without RGBA-support */
        background:rgba(204,204,204,0.5);
    }
     #map_canvas {
        -webkit-box-shadow:0 0 10px #bfdeff;
        -moz-box-shadow:0 0 5px #bfdeff;
        box-shadow:0 0 7px #bfdeff;
        float:right;
        height:100%;
        width:100%;
        height: 100px;
        width: 100px;
        padding:10px;
        margin-right:3px;
        vertical-align:top;
    }
    #listing {
        font:18pt "Nilland";
        letter-spacing:5px;
        text-align:center;
        padding:3px;
        height:40%;
        width:50%;
        background:#ccc;
        margin-bottom: 10px;
    /* Fallback for older browsers without RGBA-support */
        background:rgba(204,204,204,0.5);
        float:left;
        }
    #footer {
        font:20px "DistrictPro-Thin";
        letter-spacing:10px;
        background-color:#fff;
        color:#000;
        text-align:center;
        padding:3px;
        width:1255px;
        background:#ccc;
        margin-top: 10px;
    /* Fallback for older browsers without RGBA-support */
        background:rgba(204,204,204,0.5);
        float:left;
    }
        .placeIcon {
      width: 32px;
      height: 37px;
      margin: 4px;
    }
    .hotelIcon {
      width: 24px;
      height: 24px;
    }
    #resultsTable {
        font:16pt "Nilland-Black";
      border-collapse: collapse;
      width: 450px;
      margin-left:90px;
      float:left;
       background:rgba(204,204,204,0.5);
    }
    #rating {
      font-size: 13px;
      font-family: Arial Unicode MS;
    }
    #keywordsLabel {
      text-align: right;
      width: 70px;
      font-size: 14px;
      padding: 4px;
      position: absolute;
    }
    .iw_table_row {
      height: 18px;
    }
    .iw_attribute_name {
      font-weight: bold;
      text-align: right;
    }

和固定代码:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Map</title>
<link href="css.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">

  var map, places, iw;
  var markers = [];
  var searchTimeout;
  var centerMarker;
  var autocomplete;
  var hostnameRegexp = new RegExp('^https?://.+?/');

  function initialize() {
    var myLatlng = new google.maps.LatLng(37.786906,-122.410156);
    var myOptions = {
      zoom: 15,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
    places = new google.maps.places.PlacesService(map);
    google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);

    document.getElementById('keyword').onkeyup = function(e) {
      if (!e) var e = window.event;
      if (e.keyCode != 13) return;
      document.getElementById('keyword').blur();
      search(document.getElementById('keyword').value);
    }

    var typeSelect = document.getElementById('type');
    typeSelect.onchange = function() {
      search();
    };

    var rankBySelect = document.getElementById('rankBy');
    rankBySelect.onchange = function() {
      search();
    };

  }

  function tilesLoaded() {
    search();
    google.maps.event.clearListeners(map, 'tilesloaded');
    google.maps.event.addListener(map, 'zoom_changed', searchIfRankByProminence);
    google.maps.event.addListener(map, 'dragend', search);
  }

  function searchIfRankByProminence() {
    if (document.getElementById('rankBy').value == 'prominence') {
      search();
    }    
  }

  function search() {
    clearResults();
    clearMarkers();

    if (searchTimeout) {
      window.clearTimeout(searchTimeout);
    }
    searchTimeout = window.setTimeout(reallyDoSearch, 500);
  }

  function reallyDoSearch() {      
    var type = document.getElementById('type').value;
    var keyword = document.getElementById('keyword').value;
    var rankBy = document.getElementById('rankBy').value;

    var search = {};

    if (keyword) {
      search.keyword = keyword;
    }

    if (type != 'establishment') {
      search.types = [type];
    }

    if (rankBy == 'distance' && (search.types || search.keyword)) {
      search.rankBy = google.maps.places.RankBy.DISTANCE;
      search.location = map.getCenter();
      centerMarker = new google.maps.Marker({
        position: search.location,
        animation: google.maps.Animation.DROP,
        map: map
      });
    } else {
      search.bounds = map.getBounds();
    }

    places.search(search, function(results, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
          var icon = 'number_' + (i+1) + '.png';
          markers.push(new google.maps.Marker({
            position: results[i].geometry.location,
            animation: google.maps.Animation.DROP,
            icon: icon
          }));
          google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
          window.setTimeout(dropMarker(i), i * 100);
          addResult(results[i], i);
        }
      }
    });
  }

  function clearMarkers() {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
    }
    markers = [];
    if (centerMarker) {
      centerMarker.setMap(null);
    }
  }

  function dropMarker(i) {
    return function() {
      if (markers[i]) {
        markers[i].setMap(map);
      }
    }
  }

  function addResult(result, i) {
    var results = document.getElementById('results');
    var tr = document.createElement('tr');
    tr.style.backgroundColor = (i% 2 == 0 ? '#F0F0F0' : '#FFFFFF');
    tr.onclick = function() {
      google.maps.event.trigger(markers[i], 'click');
    };

    var iconTd = document.createElement('td');
    var nameTd = document.createElement('td');
    var icon = document.createElement('img');
    icon.src = 'number_' + (i+1) + '.png';
    icon.setAttribute('class', 'placeIcon');
    icon.setAttribute('className', 'placeIcon');
    var name = document.createTextNode(result.name);
    iconTd.appendChild(icon);
    nameTd.appendChild(name);
    tr.appendChild(iconTd);
    tr.appendChild(nameTd);
    results.appendChild(tr);
  }

  function clearResults() {
    var results = document.getElementById('results');
    while (results.childNodes[0]) {
      results.removeChild(results.childNodes[0]);
    }
  }

  function getDetails(result, i) {
    return function() {
      places.getDetails({
          reference: result.reference
      }, showInfoWindow(i));
    }
  }

  function showInfoWindow(i) {
    return function(place, status) {
      if (iw) {
        iw.close();
        iw = null;
      }

      if (status == google.maps.places.PlacesServiceStatus.OK) {
        iw = new google.maps.InfoWindow({
          content: getIWContent(place)
        });
        iw.open(map, markers[i]);        
      }
    }
  }

  function getIWContent(place) {
    var content = '';
    content += '<table>';
    content += '<tr class="iw_table_row">';
    content += '<td style="text-align: left"><img class="hotelIcon" src="' + place.icon + '"/></td>';
    content += '<td><b><a href="' + place.url + '">' + place.name + '</a></b></td></tr>';
    content += '<tr class="iw_table_row"><td class="iw_attribute_name">Address:</td><td>' + place.vicinity + '</td></tr>';
    if (place.formatted_phone_number) {
      content += '<tr class="iw_table_row"><td class="iw_attribute_name">Telephone:</td><td>' + place.formatted_phone_number + '</td></tr>';      
    }
    if (place.rating) {
      var ratingHtml = '';
      for (var i = 0; i < 5; i++) {
        if (place.rating < (i + 0.5)) {
          ratingHtml += '&#10025;';
        } else {
          ratingHtml += '&#10029;';
        }
      }
      content += '<tr class="iw_table_row"><td class="iw_attribute_name">Rating:</td><td><span id="rating">' + ratingHtml + '</span></td></tr>';
    }
    if (place.website) {
      var fullUrl = place.website;
      var website = hostnameRegexp.exec(place.website);
      if (website == null) { 
        website = 'http://' + place.website + '/';
        fullUrl = website;
      }
      content += '<tr class="iw_table_row"><td class="iw_attribute_name">Website:</td><td><a href="' + fullUrl + '">' + website + '</a></td></tr>';
    }
    content += '</table>';
    return content;
  }

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

</script>

</head>
<body>
 <div id="header">
      <h1>
        HEADER
      </h1>
    </div>
<div id="listing">
    Keywords:
    <input id="keyword" type="text" value="Mexican,Italian,Chinese..." />
  <div id="controls">
    <span id="typeLabel">
      Type:
    </span>
    <select id="type">
      <option value="bar">Bars</option>
      <option value="cafe">Cafe</option>
      <option value="restaurant" selected="selected">Restaurants</option>
      </select>
    <span id="rankByLabel">
      Rank by:
    </span>
    <select id="rankBy">
      <option value="prominence">Prominence</option>
      <option value="distance" selected="selected">Distance</option>
    </select>
  </div>
  </div>

  <div id="map_canvas"></div>

  <div id="listing" style="overflow-y: scroll; height:400px;"><table id="resultsTable"><tbody id="results"></tbody></table></div>

 <div id="footer">
        Credits to Google Maps and <a href=
        "http://mapicons.nicolasmollet.com">Maps Icons Collection</a>
    </div>
</body>
</html>