API Карт Google обновляет маркер из другого скрипта - PullRequest
0 голосов
/ 06 сентября 2018

Привет, у меня есть следующий код. Я инициировал свои карты Google внутри скрипта, как указано в документации. Я хочу обновить маркер из другого скрипта в коде. Как бы я это сделал? Когда маркер обновится, он будет активен или страница должна быть обновлена? Если страница должна быть обновлена, как я могу сделать это, чтобы она обновлялась?

<!--The div element for the map -->
         <div id="map">
          <% var getLat = lat %>
          <% var getlong = long %> 
         <script>
            // Initialize and add the map
            function initMap() {
             // The location of city  
              var passLat = <%= getLat  %>;
              var passLong = <%= getlong  %>;
              var city = {lat: passLat, lng: passLong}; 

              // The map, centered at city 
              var map = new google.maps.Map(
              document.getElementById('map'), {zoom: 10, center: city});
              // The marker, positioned at Uluru
              var marker = new google.maps.Marker({position: city, map: map});

             }                            
         </script>
            <script 
            src="https://maps.googleapis.com/maps/api/js?key=MYAPI&callback=initMap" defer>
          </script>
      </div>
      <h3 id = "LocalPhotos"> What the Local Area Looks Like:</h3>
      <div id = "flick">
          <script>
              var city2 = {lat: 27, lng: 152}; 
              marker.position(city2);
              //update the marker here. But this code doesn't work

              </script>

      </div>

1 Ответ

0 голосов
/ 06 сентября 2018

У вас есть три вопроса:

  1. В настоящее время ваша переменная marker является локальной для функции initMap. Переместите его в глобальную область:
// in global scope, outside the function
var marker;
function initMap() {
  // The location of city  
  var passLat = <%= getLat  %>;
  var passLong = <%= getlong  %>;
  var city = {lat: passLat, lng: passLong}; 

  // The map, centered at city 
  var map = new google.maps.Map(document.getElementById('map'), 
    {zoom: 10, center: city});
  // The marker, positioned at Uluru
  // initialize the global variable (remove the "var")
  marker = new google.maps.Marker({position: city, map: map});
}  
  1. marker не имеет документированного position члена, используйте документированный setPosition метод:
var city2 = {
  lat: 27,
  lng: 152
};
marker.setPosition(city2);
  1. Другая проблема заключается в том, что код, который устанавливает положение маркера, запускается до загрузки API и запускается код, который создает карту. Это можно исправить с помощью setTimeout следующим образом (но эта проблема должна решаться в контексте вашего приложения, setTimeout - это реальная проблема):
var city2 = {
  lat: 27,
  lng: 152
};
setTimeout(function() {
marker.setPosition(city2);
map.setCenter(marker.getPosition());
//update the marker here. But this code doesn't work
}, 5000)

подтверждение концепции скрипки

фрагмент кода:

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<!--The div element for the map -->
<div id="map">
  <script>
    var marker, map;
    // Initialize and add the map
    function initMap() {
      // The location of city  
      var passLat = 37.4419;
      var passLong = -122.1419;
      var city = {
        lat: passLat,
        lng: passLong
      };

      // The map, centered at city 
      map = new google.maps.Map(
        document.getElementById('map'), {
          zoom: 10,
          center: city
        });
      // The marker, positioned at Uluru
      marker = new google.maps.Marker({
        position: city,
        map: map
      });

    }
  </script>
  <script src="https://maps.googleapis.com/maps/api/js?callback=initMap" defer>
  </script>
</div>
<h3 id="LocalPhotos"> What the Local Area Looks Like:</h3>
<div id="flick">
  <script>
    // the middle of the pacific ocean?
    var city2 = {
      lat: 27,
      lng: 152
    };
    setTimeout(function() {
      marker.setPosition(city2);
      map.setCenter(marker.getPosition());
      //update the marker here. But this code doesn't work
    }, 5000)
  </script>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...