2016-05-07 3 views
0

Я использую этот код, чтобы отобразить карту на своем сайтеGoogle Maps в Java Script не работает на второй клик

<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>Google Maps JavaScript API v3 Example: Geocoding Simple</title> 
<script src="http://maps.googleapis.com/maps/api/js"></script> 
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
<script type="text/javascript"> 
    var geocoder; 
    var map; 
    var address =""; 

    function map(){ 
    alert("insisde"); 
    if(!document.getElementById('val').value){ 
    alert('Enter Val 1 Value'); 
    } 
    else if (!document.getElementById('val2').value){ 
    alert('Enter Val 2 Value'); 
    } 
    else if (!document.getElementById('val3').value){ 
    alert('Enter Val 3 Value'); 
    } 
    else{ 
    address += document.getElementById('val').value; 
    address += document.getElementById('val2').value; 
    address += document.getElementById('val3').value; 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(-34.397, 150.644); 
    var myOptions = { 
     zoom: 8, 
     center: latlng, 
    mapTypeControl: true, 
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}, 
    navigationControl: true, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    if (geocoder) { 
     geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) { 
      map.setCenter(results[0].geometry.location); 
      map.setZoom(13); 
      var infowindow = new google.maps.InfoWindow(
       { content: '<b>'+address+'</b>', 
        size: new google.maps.Size(150,50) 
       }); 

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

       title:address 
      }); 
      google.maps.event.addListener(marker, 'click', function() { 
       infowindow.open(map,marker); 
      }); 

      } else { 
      alert("No results found"); 
      } 
     } else { 
      alert("Geocode was not successful for the following reason: " + status); 
     } 
     }); 
    } 
    } 
    } 

</script> 
</head> 
<body style="margin:0px; padding:0px;" > 

<input id="val" /> 
<input id="val2" /> 
<input id="val3" /> 
<button onClick="map()" >Add Map</button> 
<div id="map_canvas" style="width:50%; height:50%;"> 
</body> 
</html> 

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

asd.html:78 Uncaught TypeError: map is not a function

ответ

0

Вам не нужно инициализировать карту на каждый раз, когда вы называете геокодер. Просто инициализируйте его при загрузке документа, а затем отобразите только маркер с результатами геокодера. Каждый раз, когда вы вызываете геокод, вы просто удаляете старый маркер с карты. Попробуйте следующее:

<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title> 
<script src="http://maps.googleapis.com/maps/api/js"></script> 
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
<script type="text/javascript"> 
    var map = null; 
    var marker = null; 

    $(document).ready(function(){ 
     var latlng = new google.maps.LatLng(-34.397, 150.644); 
     var myOptions = { 
     zoom: 1, 
     center: latlng, 
     mapTypeControl: true, 
     mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}, 
     navigationControl: true, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 
     map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    }); 

    function geocode(){ 
     if(marker) marker.setMap(null); 
     var geocoder; 
     var address =""; 
    if(!document.getElementById('val').value){ 
    alert('Enter Val 1 Value'); 
    } 
    else if (!document.getElementById('val2').value){ 
    alert('Enter Val 2 Value'); 
    } 
    else if (!document.getElementById('val3').value){ 
    alert('Enter Val 3 Value'); 
    } 
    else{ 
    address += document.getElementById('val').value + " "; 
    address += document.getElementById('val2').value + " "; 
    address += document.getElementById('val3').value; 
    geocoder = new google.maps.Geocoder(); 

    if (geocoder) { 
     geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) { 
      map.setCenter(results[0].geometry.location); 
      map.setZoom(13); 
      var infowindow = new google.maps.InfoWindow(
       { content: '<b>'+address+'</b>', 
        size: new google.maps.Size(150,50) 
       }); 

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

       title:address 
      }); 
      google.maps.event.addListener(marker, 'click', function() { 
       infowindow.open(map,marker); 
      }); 

      } else { 
      alert("No results found"); 
      } 
     } else { 
      alert("Geocode was not successful for the following reason: " + status); 
     } 
     }); 
    } 
    } 
    } 

</script> 
</head> 
<body style="margin:0px; padding:0px;" > 

<input id="val" /> 
<input id="val2" /> 
<input id="val3" /> 
<button onClick="geocode()" >Geocode</button> 
<div id="map_canvas" style="width:50%; height:50%;"> 
</body> 
</html> 
+0

Это было потрясающе спасибо браку .. :) – user3692459

Смежные вопросы