Embedding a Google map

2019-07-16 17:57发布

问题:

I have embedded a Google Map in my website. I want to change its location according to user input. How can I do this?

I tried to copy the link of the location and assign it to the iframe src:

    $("iframe").attr("src", "https://maps.google.co.in/maps?q=USA&hl=en&ll=37.09024,-95.712891&spn=131.016476,346.289063&sll=23.259933,77.412615&sspn=0.178842,0.338173&oq=usa&doflg=ptm&hnear=United+States&t=m&z=2");

but the iframe is not loading the map.

回答1:

Take a look at this :)

<!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"/>  
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />  
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>  
<script type="text/javascript"> 
// Initiate map 
function initialize(data) { 
  // Make position for center map 
  var myLatLng = new google.maps.LatLng(data.lng, data.lat); 

  // Map options  
  var myOptions = { 
    zoom: 10, 
    center: myLatLng, 
    mapTypeId: google.maps.MapTypeId.HYBRID 
  }; 

  // Initiate map 
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

  // Info window element 
  infowindow = new google.maps.InfoWindow(); 

  // Set pin 
  setPin(data); 
} 
// Show position 
function setPin(data) { 
  var pinLatLng = new google.maps.LatLng(data.lng, data.lat); 
  var pinMarker = new google.maps.Marker({ 
    position: pinLatLng, 
    map: map, 
    data: data 
  }); 

  // Listen for click event  
  google.maps.event.addListener(pinMarker, 'click', function() { 
    map.setCenter(new google.maps.LatLng(pinMarker.position.lat(), pinMarker.position.lng())); 
    map.setZoom(18); 
    onItemClick(event, pinMarker); 
  }); 
} 
// Info window trigger function 
function onItemClick(event, pin) { 
  // Create content  
  var contentString = pin.data.text + "<br /><br /><hr />Coordinate: " + pin.data.lng +"," + pin.data.lat; 

  // Replace our Info Window's content and position 
  infowindow.setContent(contentString); 
  infowindow.setPosition(pin.position); 
  infowindow.open(map) 
} 
</script>  
</head>  
<body onload="initialize({lat:-3.19332,lng:55.952366,text:'<h2>Edinburgh</h2><i>Nice city!</i>'})"> 
  <div id="map_canvas">  
</div>  
</body>  
</html> 


回答2:

Try to use the GoogleMaps JavaScript API. The offer way more control (geocode, searching, custom marker, etc...) over the map then just embedding a iframe.