Google地图API已加载但无法在网页中显示

时间:2016-02-22 07:35:14

标签: javascript ajax google-maps google-maps-api-3

我正在使用自定义谷歌API,我成功地在其他网页中使用。在某些网页中无法正常工作。地图API已成功加载,但无法在网页中显示。

按照我的代码:

<html>
<head>
<title>test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script type="text/javascript">
$(document).ready(function() {  
var mapCenter = new google.maps.LatLng(-33.921152, 151.164954); //Google map Coordinates
var map;
var markers = [];
map_initialize(); // initialize google map

//############### Google Map Initialize ##############
function map_initialize()
{
        var googleMapOptions = 
        { 
            center: mapCenter, // map center
            zoom: 17, //zoom level, 0 = earth view to higher value
            //maxZoom: 18,
            //minZoom: 16,
            zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL //zoom control size
        },
            scaleControl: true, // enable scale control
            mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
        };

        map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);         

        //Load Markers from the XML File, Check (map_process.php)
        $.get("map_process.php", function (data) {
            $(data).find("marker").each(function () {
                  var name      = $(this).attr('name');
                  var address   = '<p>'+ $(this).attr('address') +'</p>';
                  var type      = $(this).attr('type');
                  var point     = new google.maps.LatLng(parseFloat($(this).attr('lat')),parseFloat($(this).attr('lng')));
                  create_marker(point, name, address, false, false, false, "icons/pin_blue.png");
            });
        }); 

        //Right Click to Drop a New Marker
        google.maps.event.addListener(map, 'rightclick', function(event) {
            //Edit form to be displayed with new marker
            var EditForm = '<p><div class="marker-edit">'+
            '<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">'+
            '<label for="pName"><span>Place Name :</span><input type="text" name="pName" class="save-name" placeholder="Enter Title" maxlength="40" /></label>'+
            '<label for="pDesc"><span>Description :</span><textarea name="pDesc" class="save-desc" placeholder="Enter Address" maxlength="150"></textarea></label>'+
            '<label id="chk" for="pType"><span>Type :</span> <select name="pType" class="save-type"><option value="restaurant">Rastaurant</option><option value="bar">Bar</option>'+
            '<option value="house">House</option></select></label>'+
            '</form>'+
            '</div></p><button name="save-marker" class="save-marker">Save Marker Details</button>';

            //Drop a new Marker with our Edit Form
            create_marker(event.latLng, 'New Marker', EditForm, true, true, true, "icons/pin_green.png");
        });

}

//############### Create Marker Function ##############
function create_marker(MapPos, MapTitle, MapDesc,  InfoOpenDefault, DragAble, Removable, iconPath)
{                 

    //new marker
    var marker = new google.maps.Marker({
        position: MapPos,
        map: map,
        draggable:DragAble,
        animation: google.maps.Animation.DROP,
        title:"Streetfighter Media",
        icon: iconPath
    });

    //Content structure of info Window for the Markers
    var contentString = $('<div class="marker-info-win">'+
    '<div class="marker-inner-win"><span class="info-content">'+
    '<h1 class="marker-heading">'+MapTitle+'</h1>'+
    MapDesc+ 
    '</span><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button>'+'<p><a title="Location" class="locc" href="http://maps.google.com/maps?q='+MapPos+'">Click here to view on google map.</a></p>'+
    '</div></div>');    


    //Create an infoWindow
    var infowindow = new google.maps.InfoWindow();
    //set the content of infoWindow
    infowindow.setContent(contentString[0]);

    //Find remove button in infoWindow
    var removeBtn   = contentString.find('button.remove-marker')[0];
    var saveBtn     = contentString.find('button.save-marker')[0];

    //add click listner to remove marker button
    google.maps.event.addDomListener(removeBtn, "click", function(event) {
        remove_marker(marker);
    });

    if(typeof saveBtn !== 'undefined') //continue only when save button is present
    {
        //add click listner to save marker button
        google.maps.event.addDomListener(saveBtn, "click", function(event) {
            var mReplace = contentString.find('span.info-content'); //html to be replaced after success
            var mName = contentString.find('input.save-name')[0].value; //name input field value
            var mDesc  = contentString.find('textarea.save-desc')[0].value; //description input field value
            var mType = contentString.find('select.save-type')[0].value; //type of marker

            if(mName =='' || mDesc =='')
            {
                alert("Please enter Name and Description!");
            }else{
                save_marker(marker, mName, mDesc, mType, mReplace); //call save marker function
            }
        });
    }

    //add click listner to save marker button        
    google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker); // click on marker opens info window 
    });

    if(InfoOpenDefault) //whether info window should be open by default
    {
      infowindow.open(map,marker);
    }
}

//############### Remove Marker Function ##############
function remove_marker(Marker)
{

    /* determine whether marker is draggable 
    new markers are draggable and saved markers are fixed */
    if(Marker.getDraggable()) 
    {
        Marker.setMap(null); //just remove new marker
    }
    else
    {
        //Remove saved marker from DB and map using jQuery Ajax
        var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
        var myData = {del : 'true', latlang : mLatLang}; //post variables
        $.ajax({
          type: "POST",
          url: "map_process.php",
          data: myData,
          success:function(data){
                Marker.setMap(null); 
                alert(data);
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(thrownError); //throw any errors
            }
        });
    }

}

//############### Save Marker Function ##############
function save_marker(Marker, mName, mAddress, mType, replaceWin)
{
    //Save new marker using jQuery Ajax
    var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
    var myData = {name : mName, address : mAddress, latlang : mLatLang, type : mType }; //post variables
    console.log(replaceWin);        
    $.ajax({
      type: "POST",
      url: "map_process.php",
      data: myData,
      success:function(data){
            replaceWin.html(data); //replace info window with new html
            Marker.setDraggable(false); //set marker to fixed
            Marker.setIcon('icons/pin_blue.png'); //replace icon
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(thrownError); //throw any errors
        }
    });
}



  var defaultBounds = new google.maps.LatLngBounds(
  new google.maps.LatLng(-33.921152, 151.164954),
  new google.maps.LatLng(-33.8474, 151.2631));
  map.fitBounds(defaultBounds);

  var marker;
  // Create the search box and link it to the UI element.
  var input = /** @type {HTMLInputElement} */(
   document.getElementById('pac-input'));
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

   var searchBox = new google.maps.places.SearchBox(
   /** @type {HTMLInputElement} */(input));

  // [START region_getplaces]
  // Listen for the event fired when the user selects an item from the
  // pick list. Retrieve the matching places for that item.
   google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();

if (places.length == 0) {
  return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
  marker.setMap(null);
}

// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
  var image = {
    url: place.icon,
    size: new google.maps.Size(71, 71),
    origin: new google.maps.Point(0, 0),
    anchor: new google.maps.Point(17, 34),
    scaledSize: new google.maps.Size(25, 25)
  };

  // Create a marker for each place.
  var marker = new google.maps.Marker({
    map: map,
    icon: image,
    title: place.name,
    position: place.geometry.location
  });

  markers.push(marker);

  bounds.extend(place.geometry.location);
}

map.fitBounds(bounds);
});
// [END region_getplaces]

 // Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
});

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="pac-input"  class="controls" type="text" placeholder="Search    Box"/>
<div id="google_map"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

您必须为地图div容器指定大小,例如:

<body>
   <input id="pac-input"  class="controls" 
                type="text" placeholder="Search    Box"/>
   <div id="google_map" style="width:500px; height: 500px;"></div>
</body>