2016-02-26 5 views
0

Я пишу код, чтобы отображать некоторые кнопки на картах, используя Google Maps V3 APi (JS).Autozoom/Autocenter с GoogleMaps Avi v3 JS

Я хотел бы использовать Autozoom и Autocenter. Для этого мне нужно использовать Bound.extends() и map.fitBounds(), тем не менее, с использованием этих функций у меня есть только одно нажатие ... не другое ... это очень странно ...

Вот мой код:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Google Maps</title> 
<script async defer 
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap"> 
</script> 
</head> 
<body> 

<div id="map" style="width: 1024px; height: 768px"></div> 

<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
    However, it seems JavaScript is either disabled or not supported by your browser. 
    To view Google Maps, enable JavaScript by changing your browser options, and then 
    try again. 
</noscript> 


<script type="text/javascript"> 
//<![CDATA[ 

    // A function to create the marker and set up the event window 
function createMarker(point,name) 
{ 
    var marker = new google.maps.Marker({position: point, title: name}); 
    google.maps.event.addListener(marker, "click", function(){ 
     marker.openInfoWindowHtml(name);}); 

    return marker; 
} 

function initMap() 
{ 

    var map = new google.maps.Map(document.getElementById('map'));//, { center: {lat: -34.397, lng: 150.644},zoom: 8}); 
    var geocoder = new google.maps.Geocoder(); 
    var optionsCarte = { 
     zoom: 8, 
     center: new google.maps.LatLng(48.5, 2.9), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 


    var map = new google.maps.Map(document.getElementById('map'), optionsCarte); 

    var bounds = new google.maps.LatLngBounds(); 

    // ========== Read paramaters that have been passed in ========== 

    // If there are any parameters at the end of the URL, they will be in location.search 
    // looking something like "[email protected],17.82" 

    // skip the first character, we are not interested in the "?" 
    var query = location.search.substring(1); 

    // split the rest at each "&" character to give a list of "argname=value" pairs 
    var pairs = query.split("&"); 

    for (var i=0; i<pairs.length; i++) 
    { 
     // break each pair at the first "=" to obtain the argname and value 
     var pos = pairs[i].indexOf("="); 
     var argname = pairs[i].substring(0,pos).toLowerCase(); 
     var value = pairs[i].substring(pos+1); 

     // process each possible argname - use unescape() if theres any chance of spaces 
     if (argname == "q") 
     { 
      var text = unescape(value); 
      var parts = text.split("@"); 

      geocoder.geocode({ 'address': parts[1]}, function(results, status) 
      { 
       if (status == google.maps.GeocoderStatus.OK) 
       { 
        map.setCenter(results[0].geometry.location);//center the map over the result 

        var title = parts[0]; 

        var marker = new google.maps.Marker({ 
         map: map, 
         position: results[0].geometry.location 
        }); 
       } else { 
        alert('Geocode was not successful for the following reason: ' + status); 
       } 
      }); 

      bounds.extend(results[0].geometry.location); 
     } 
    } 

    map.fitBounds(bounds) 
    map.panToBounds(bounds); 
    map.setCenter(bounds.getCenter()); 

} 

</script> 

для того, чтобы выполнить мой вызов, я должен сделать это:

http://XX.XX.XX.XX/[email protected]&[email protected]

Любая идея, где моя ошибка? Я думаю, что это bound.extend fonction.

+0

'bounds.extend (результаты [0] .geometry.location);' должно быть внутри функции результата геокодирования. Вероятно, вы получите сообщение об ошибке в консоли браузера. – alalp

+0

Спасибо :) это нормально :) –

ответ

1

Вы должны переместить код, связанный со связанным, масштабирования и центра внутри цикла

поэтому сначала у вас есть геокодирования результат на (и поэтому вы не получите сообщение об ошибке для этого) и второй вы можете продлить связанная инкрементально ..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Google Maps</title> 
<script async defer 
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap"> 
</script> 
</head> 
<body> 

<div id="map" style="width: 1024px; height: 768px"></div> 

<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
    However, it seems JavaScript is either disabled or not supported by your browser. 
    To view Google Maps, enable JavaScript by changing your browser options, and then 
    try again. 
</noscript> 


<script type="text/javascript"> 
//<![CDATA[ 

    // A function to create the marker and set up the event window 
function createMarker(point,name) 
{ 
    var marker = new google.maps.Marker({position: point, title: name}); 
    google.maps.event.addListener(marker, "click", function(){ 
     marker.openInfoWindowHtml(name);}); 

    return marker; 
} 

function initMap() 
{ 

    var map = new google.maps.Map(document.getElementById('map'));//, { center: {lat: -34.397, lng: 150.644},zoom: 8}); 
    var geocoder = new google.maps.Geocoder(); 
    var optionsCarte = { 
          zoom: 8, 
          center: new google.maps.LatLng(48.5, 2.9), 
          mapTypeId: google.maps.MapTypeId.ROADMAP 
         }; 


    var map = new google.maps.Map(document.getElementById('map'), optionsCarte); 

    var bounds = new google.maps.LatLngBounds(); 

    // ========== Read paramaters that have been passed in ========== 

    // If there are any parameters at the end of the URL, they will be in location.search 
    // looking something like "[email protected],17.82" 

    // skip the first character, we are not interested in the "?" 
    var query = location.search.substring(1); 

    // split the rest at each "&" character to give a list of "argname=value" pairs 
    var pairs = query.split("&"); 

    for (var i=0; i<pairs.length; i++) 
    { 
     // break each pair at the first "=" to obtain the argname and value 
     var pos = pairs[i].indexOf("="); 
     var argname = pairs[i].substring(0,pos).toLowerCase(); 
     var value = pairs[i].substring(pos+1); 

     // process each possible argname - use unescape() if theres any chance of spaces 
     if (argname == "q") 
     { 
      var text = unescape(value); 
      var parts = text.split("@"); 

      geocoder.geocode({ 'address': parts[1]}, function(results, status) 
      { 
       if (status == google.maps.GeocoderStatus.OK) 
       { 
       map.setCenter(results[0].geometry.location);//center the map over the result 

           var title = parts[0]; 


       var marker = new google.maps.Marker({ 
       map: map, 
       position: results[0].geometry.location}); 

       bounds.extend(results[0].geometry.location); 
       map.fitBounds(bounds) 
       map.panToBounds(bounds); 
       map.setCenter(bounds.getCenter());    
       } else { 
       alert('Geocode was not successful for the following reason: ' + status); 
       } 

      }); 

      //bounds.extend(results[0].geometry.location); 
     } 
    } 

    //map.fitBounds(bounds) 
    ///map.panToBounds(bounds); 
    //map.setCenter(bounds.getCenter()); 

} 

</script> 
+0

Спасибо большое, все в порядке :) –