How to dynamically change the script src?

限于喜欢 提交于 2019-12-13 09:50:14

问题


I'm trying to dynamically change the region depends on what I select in a dropdown field.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?region=DK"></script>

Can someone help me figure this out?


回答1:


You can load JavaScript dynamically after page has loaded, but remember: once you've loaded it, you can't unload JavaScript in an active page. It is stored in the browsers memory pool. You can reload a page, which will clear the active scripts, and start over. Alternatively you could override the functions that you've got set.

With this said. Here's how to change the script after page load with javascript:

<select onChange="changeRegion(this.value);">
    <option value="-">Select region</option>
    <option value="SE">Sweden</option>
    <option value="DK">Denmark</option>
</select>

<div id="output">
    <script id="map" type="text/javascript" src="https://maps.googleapis.com/maps/api/js?region=DK"></script>
</div>

<script type="text/javascript">
function changeRegion(value)
{
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "https://maps.googleapis.com/maps/api/js?region=" + value;
    s.innerHTML = null;
    s.id = "map";
    document.getElementById("output").innerHTML = "";
    document.getElementById("output").appendChild(s);
}
</script>



回答2:


Try this..

<html>
 <head>
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> 
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>  
 </head>
 <body>
  <h1>Google Maps Autocomplete Search Sample</h1>
  <div align="left">
   <input type="text" value="" id="searchbox" style=" width:800px;height:30px; font-size:15px;">
  </div>
  <div align="left" id="map" style="width:800px; height: 600px; margin-top: 10px;">

  </div>

 </body>
</html>
<script type="text/javascript">
 $(document).ready(function(){

  var mapOptions = {
       zoom: 10,
       mapTypeId: google.maps.MapTypeId.ROADMAP,
       center: new google.maps.LatLng(41.06000,28.98700)
     };

  var map = new google.maps.Map(document.getElementById("map"),mapOptions);

  var geocoder = new google.maps.Geocoder();  

     $(function() {
         $("#searchbox").autocomplete({

           source: function(request, response) {

          if (geocoder == null){
           geocoder = new google.maps.Geocoder();
          }
             geocoder.geocode( {'address': request.term }, function(results, status) {
               if (status == google.maps.GeocoderStatus.OK) {

                  var searchLoc = results[0].geometry.location;
               var lat = results[0].geometry.location.lat();
                  var lng = results[0].geometry.location.lng();
                  var latlng = new google.maps.LatLng(lat, lng);
                  var bounds = results[0].geometry.bounds;

                  geocoder.geocode({'latLng': latlng}, function(results1, status1) {
                      if (status1 == google.maps.GeocoderStatus.OK) {
                        if (results1[1]) {
                         response($.map(results1, function(loc) {
                        return {
                            label  : loc.formatted_address,
                            value  : loc.formatted_address,
                            bounds   : loc.geometry.bounds
                          }
                        }));
                        }
                      }
                    });
            }
              });
           },
           select: function(event,ui){
      var pos = ui.item.position;
      var lct = ui.item.locType;
      var bounds = ui.item.bounds;

      if (bounds){
       map.fitBounds(bounds);
      }
           }
         });
     });   
 });
</script>



回答3:


You should avoid loading the Google Maps API more than once. If possible you should consider leaving out that script tag and instead add it through JavaScript once the dropdown (region) selection has been made.

EDIT:

Let's say you have a dropdown like this:

<select id="regionSelector" onchange="loadGoogleMaps()">
  <option value="">Select region to use Google Maps:</option>
  <option value="DK">Denmark</option>
  <option value="SE">Sweden</option>
</select>

Adding the script would be something like:

function loadGoogleMaps() { 

    var selectedRegion = document.getElementById("regionSelector").value;

    if(selectedRegion === '') {
       return;
    }

    var head= document.getElementsByTagName('head')[0];
    var script= document.createElement('script');
    script.type= 'text/javascript';
    script.src= 'https://maps.googleapis.com/maps/api/js?region=' + selectedRegion;
    head.appendChild(script);
}

More info on async loading of the Google Maps API: https://developers.google.com/maps/documentation/javascript/examples/map-simple-async



来源:https://stackoverflow.com/questions/29531097/how-to-dynamically-change-the-script-src

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!