Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 18.05.2019, 15:11
Интересующийся
Отправить личное сообщение для Vladiiimir Посмотреть профиль Найти все сообщения от Vladiiimir
 
Регистрация: 18.05.2019
Сообщений: 19

Обновление карты Google для новых координат
Здравствуйте!

Подскажите пожалуйста, как правильно написать функцию, которая перегружала бы кару Google в новых координатах с маркером по запросу пользователя?

Подтянуть карту у меня получилось, а вот обновить её не получается.

<html>
  <head>
    <title>Simple Map</title>
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 50%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    
     <script>
      function initMap() {
       var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(57,58),
          zoom: 8
        });
      }
    </script>
    
    <script>
        function UpdateGoogleMap(latitude, longitude) {
 
             var   map = new google.maps.Map(document.getElementById('map'), {
                zoom: 15,
                center: new google.maps.LatLng(latitude,longitude),
            });
 
            var marker = new google.maps.Marker({
                position: map.getCenter(),
                map: map,
                title: 'Это здесь'
            });
        }
      </script>
      <script src="https://maps.googleapis.com/maps/api/js?key=XXX&callback=initMap"
      async defer></script>    
  </head>
  <body>
        <form name="info"> 
                Широта: <input type="text" name="xfirst" align="left" size=20><br><br>
                Долгота: <input type="text" name="xend" align="left" size=20><br><br>
 
                <input type="button" value="Построить" name="buttonDraw" align="center" size=15 onclick="UpdateGoogleMap('xfirst.value','xend.value')"><br>
        </form>
 
        <div id="map">               
        </div>
    
  </body>
</html>
Ответить с цитированием
  #2 (permalink)  
Старый 18.05.2019, 16:01
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,064

Vladiiimir,
var map, marker;

function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(57, 58),
        zoom: 8
    });
}

function UpdateGoogleMap(latitude, longitude) {
    map.setCenter({
        lat: latitude,
        lng: longitude
    });
    marker && marker.setMap(null);
    marker = new google.maps.Marker({
        position: {
            lat: latitude,
            lng: longitude
        },
        map: map,
        title: "Это здесь"
    });
};


onclick="UpdateGoogleMap(+xfirst.value,+xend.value)"
Ответить с цитированием
  #3 (permalink)  
Старый 18.05.2019, 19:15
Интересующийся
Отправить личное сообщение для Vladiiimir Посмотреть профиль Найти все сообщения от Vladiiimir
 
Регистрация: 18.05.2019
Сообщений: 19

рони,
Скажите, а в каком части кода должны быть объявлены "var map, marker"?
Извините за возможно тупой вопрос, я только начал изучать javascript.
Я пытаюсь сделать вот так, но карта непрогружается вообще:
<html>
  <head>
    <title>Simple Map</title>
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 50%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
      }
    </style>
   
     <script>
      function initMap() {
          map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(51.754207,55.106578),
          zoom: 8
        });
      }
    </script>
    var map, marker;
    <script>
        function UpdateGoogleMap(latitude=51.754207, longitude=55.106578) {
            map.setCenter(
                {lat: latitude,
                 lng: longitude}
            );
            marker && marker.setMap(null);
            marker=new google.maps.marker({
                position:{
                 lat: latitude,
                 lng: longitude
                },
            map: map,
            title: 'Это здесь'
            });
     };
      </script>
      <!-- -->
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCWH__g2XMzhes7PIk-8v2MbBSZTgMnBSg&callback=UpdateGoogleMap"
      async defer></script>
      
  </head>
  <body>
        <form name="info"> 
                Широта: <input type="text" name="xfirst" align="left" size=20><br><br>
                Долгота: <input type="text" name="xend" align="left" size=20><br><br>

                <input type="button" value="Построить" name="buttonDraw" align="center" size=15 onclick="UpdateGoogleMap(+xfirst.value,+xend.value)"><br>
        </form>

        <div id="map">               
        </div>
    
  </body>
</html>
Ответить с цитированием
  #4 (permalink)  
Старый 18.05.2019, 19:28
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,064

Vladiiimir,
<html>
  <head>
    <title>Simple Map</title>
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 50%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>

     <script>

var map, marker;

function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(51.754207,55.106578),
        zoom: 8
    });
}

function UpdateGoogleMap(latitude, longitude) {
    latitude = (latitude && +latitude)||51.754207;
    longitude = (longitude && +longitude)||55.106578;
    map.setCenter({
        lat: latitude,
        lng: longitude
    });
    marker && marker.setMap(null);
    marker = new google.maps.Marker({
        position: {
            lat: latitude,
            lng: longitude
        },
        map: map,
        title: "Это здесь"
    });
};

</script>
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCWH__g2XMzhes7PIk-8v2MbBSZTgMnBSg&callback=initMap"
      async defer></script>
  </head>
  <body>
        <form name="info">
                Широта: <input type="text" name="xfirst" align="left" size=20 ><br><br>
                Долгота: <input type="text" name="xend" align="left" size=20 ><br><br>

                <input type="button" value="Построить" name="buttonDraw" align="center" size=15 onclick="UpdateGoogleMap(xfirst.value,xend.value)"><br>
        </form>

        <div id="map">
        </div>

  </body>
</html>
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Изменить центр карты Google Maps Neo54213 Общие вопросы Javascript 4 03.08.2017 11:41
Вытащить картинку из JSON для Google Maps claudsp jQuery 0 29.07.2011 01:16
Что использует google для настройки личной страницы?? m00 Общие вопросы Javascript 3 04.05.2010 18:06
Переодическое обновление значений для графика, функция для обновления значений yupa87 Общие вопросы Javascript 0 09.07.2009 14:48