Jump to content
  • 0

Несколько HTML-маркеров на карте Google


PeterLS
 Share

Question

Здравствуйте! Подскажите, пожалуйста, что не так делаю?.. Почему-то пишет что функция setMap не определена (здесь 37 строка в js коде)!

var o = document.getElementById("map-canvas");if (o) {    //карта    mapCenter = new google.maps.LatLng(56.528960, 84.967544);    var mapOptions = {        zoom: 15,        center: mapCenter,        scrollwheel: false,        mapTypeId: google.maps.MapTypeId.ROADMAP    };    var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);    //элементы    var li_points = $('#map-points').find('li'), options = [], pLatLng = [];    if (li_points.length > 0) {        li_points.each(function(i){            var $pt = $(this);            if ($pt.data('x') && $pt.data('y') && $pt.data('type')) {                pLatLng[i] = new google.maps.LatLng($pt.data('x'), $pt.data('y'));                options[i] = {                    id: i,                    map: map,                    latLng: pLatLng[i],                    className: 'map-marker ' + $pt.data('type')                }            }        });    }    for (var i in options) {        function MapMarker(options) {            this.latLng = options.latLng;            this.map = options.map;            this.className = options.className;            this.id = options.id;            this.content = '';            this.setMap(options.map);        }        var marker = new MapMarker(options[i]);        //действие при клике        var markers = [];        markers[marker.id] = marker;        $(document).on('click', '.map-marker', function() {            console.log(marker.id);        });        MapMarker.prototype = new google.maps.OverlayView();        MapMarker.prototype.draw = function() {            var me = this;            var div = this.div_;            if (!div) {                div = this.div_ = document.createElement('div');                div.id = this.id;                div.className = this.className;                var panes = this.getPanes();                panes.overlayImage.appendChild(div);            }            var point = this.getProjection().fromLatLngToDivPixel(this.latLng);            if (point) {                div.style.left = point.x - 20 + 'px';                div.style.top = point.y - 55 + 'px';            }        };    }}
<div id="map-canvas"></div><ul id="map-points">    <li data-x="56.528960" data-y="84.967544" data-type="running">Point 1</li>    <li data-x="57.528960" data-y="83.967544" data-type="running">Point 2</li></ul>
body {margin: 0;}#map-canvas {  width: 100%;  height: 100vh;  margin: auto;}#map-points {display: none;}.map-marker.running {background-image: url(http://d30y9cdsu7xlg0.cloudfront.net/png/27587-84.png);}.map-marker {  width: 45px;  height: 45px;  background: #485F6E center no-repeat;  background-size: 80%;  position: relative;  z-index: 30;  cursor: pointer;}.map-marker:after {  position: absolute;  left: 50%;  bottom: -8px;  ;  width: 0;  height: 0;  border-left: 8px solid transparent;  border-right: 8px solid transparent;  border-top: 8px solid #485F6E;  content: " ";}.map-marker:hover {  background-color: #39c360;  transition: 0.3s background-color;}.map-marker:hover:after {  border-top-color: #39c360;  transition: 0.3s border-top-color;} 

Только не ругайтесь за мой корявый код.. Только начинаю..

Edited by PeterLS
Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Similar Content

    • By jksnf
      Не работает transition при появлений модального окна:
      <a class="btn">Modal</a> <div class="modal"> <div class="overlay"> <div class="content"> <a class="close">X</a> <h1>Title</h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Sunt repellat asperiores rerum animi officiis minus corporis iure voluptate accusantium, ut optio ratione iusto nemo delectus. Quasi illum libero dolorum neque?</p> </div> </div> </div> //scss .modal .overlay{ position: fixed; top: 0;left: 0; width: 100%;height: 100%; background: rgba($color: #000000, $alpha: .8); z-index: 1; display: none; } .modal .content{ width: 500px;height: 200px; position: absolute; top: 50%;left: 50%; transform: translate(-50%, -50%); background-color: #fff; z-index: 2; text-align: center; display: none; a{ line-height: 30px; font-weight: bold; color: #fff; top: -50px;; position: absolute; right: -50px; font-size: 40px; padding: 10px; } h1{ margin-bottom: 20px; } } .modal.active .overlay{ display: block; } .modal.active .content{ display: block; } //Jquery $(document).ready(function(){ $(".btn, .close").click(function() { $(".modal").toggleClass("active") }) }) Я понимаю что на display не работает transition. но и нельзя ставить opacity т.к перекрывает контент сзади него изначально.

      Что делать?
    • By KatiaBeing
      Подскажите пожалуйста, как правильно сделать кастомный список стран используя API.
      Вот fetch код:
       
      const countryList = document.querySelector('.form-list.country'); fetch('https://restcountries.com/v3.1/all').then(res => { return res.json(); }).then(data => { let output = ''; data.forEach(country => { output += `<li class="form-item" data-value="${country.name.common}">${country.name.common}</li>`; countryList.innerHTML = output; }); }).catch(err => { console.log(err); }); полный код html, css, js Во втором списке "Country" список формируется, но название страны не поставляется в форму, а атрибут "data-value="" " в инпут ниже. В первом списке "Guests Amount" все ок, т.к. данные прописаны в html. Нужен такой же, но со странами.
      Сразу скажу, с тегом select все работает, но мне нужна стилизованная выпадашка. Заранее спасибо.
    • By IsayR
      Всем привет! Подскажите, пожалуйста, как правильно сделать раскрывающиеся блоки со скрытым содержанием внутри? У меня в принципе все работает, блок открывается и закрывается, НО если я нажимаю на блок, а не на стрелочку, она у меня остается в таком же положении(а она должна у меня меняться, когда блок открывается), и получается куча мала, и выглядит это не очень презентабельно. Подскажите, пожалуйста!
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper-div"> <div class="div"> <div class="window-one"> <h3 class="title"> Заголовок 1 </h3> <div class="arrow-test"></div> </div> <div class="window-two"> <div class="text">Текст 1</div> </div> </div> </div> <div class="wrapper-div"> <div class="div"> <div class="window-one"> <h3 class="title"> Заголовок 2 </h3> <div class="arrow-test"></div> </div> <div class="window-two"> <div class="text">Текст 2</div> </div> </div> </div> <div class="wrapper-div"> <div class="div"> <div class="window-one"> <h3 class="title"> Заголовок 3 </h3> <div class="arrow-test"></div> </div> <div class="window-two"> <div class="text">Текст 3</div> </div> </div> </div> .div{ border: 1px solid #3A444E; border-radius: 10px; width: 300px; height: 64px; overflow: hidden; } .div.open { height: auto; background: #000; color: #fff; } .window-one { display: flex; align-items: center; justify-content: space-between; } .title { margin-bottom: 20px; } .arrow-test { content: ''; background: url('http://cdn.onlinewebfonts.com/svg/img_387044.png') no-repeat center center / 100%; width: 30px; height: 30px; cursor: pointer; } .arrow-test.open { content: ''; background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Eo_circle_yellow_arrow-up.svg/1024px-Eo_circle_yellow_arrow-up.svg.png') no-repeat center center / 100%; width: 30px; height: 30px; cursor: pointer; } $('.div, .arrow-test').click( function(){ $(this).toggleClass('open')});  
    • By Алеся
      Всем привет! Хотела бы представить свою работу новичка на обсуждение для получения конструктивной критики и/или советов, взглядов что можно улучшить или изменить, общее впечатление, конечно, тоже интересует.   https://alesia-k.github.io/Tajam-template/
      Обратите, пожалуйста, внимание на:
      - блок "MEET OUR AMAZING TEAM". Немного не нравится как смещаются item при наведении мыши, как будто немного дергаются. Так ли по-вашему это должно работать или такое поведение блока нужно изменить?
      - инпут "subscribe" в футторе. При клике на инпут, немного смещается и сам инпут, и рядом стоящая кнопка. Было бы классно, если бы подкинули идею как сделать, чтобы такого не было.
      - и почему-то при клике на <a href="tel:(+62)2122243333">(+62)21-2224 3333</a>   не идет процесса соединения.
      Заранее спасибо!
    • By Only091
      Помогите пожалуйста, не получается сделать постраничную навигацию. Делал все по урокам. в Итоге получилось сделать два разных каталога один с фильтрами другой с постраничной навигацией. И теперь я пытаюсь объединить два каталога. Но не получается. Сами файлы урока в архике каталог. Буду очень благодарен если мне помогут! catalog.phpcatalogDB.js
      каталог.7z
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy