Answer the question
In order to leave comments, you need to log in
How to change addresses on click of one button on Google map api JavaScript?
The company has three addresses in contacts on the Google map, there is also a button by clicking on which, one address changes to the second and so on when clicked.
The script has three var markers, three variables var myLatLng1 = {lat: 59.910726, lng: 30.318788}; with a coordinate value assigned and a map map, there is also an array var arrLatLng = [myLatLng1, myLatLng2, myLatLng3] consisting of coordinates. There is a button click function. I'm just starting to learn JS and it seems to me that by clicking on the button, the var i variable, which is equal to zero, should change to 1, thereby in the map object in the property (I don't know if I called the "property" correctly) center: arrLatLng [i] should change the serial number of the array element and, accordingly, the address on the map should change. But that doesn't happen. And if it did change, what would happen if you click on the button more than three times, i.e. how to loop the function?
Here is the code, I hope everything is clear:
jQuery(document).ready(function () {
function initMap() {
var myLatLng1 = {lat: 59.910726, lng: 30.318788}; // адрес 'Цветочная улица 50'
var myLatLng2 = {lat: 59.888609, lng: 30.323378}; // адрес 'Заставская улица 30'
var myLatLng3 = {lat: 59.889525, lng: 30.330591}; // адрес 'Цветочная улица, 10А'
var arrLatLng = [myLatLng1, myLatLng2, myLatLng3]; // массив из адресов
var i = 2; //переменная указывающая порядковый номер одного из элементов массива
$(function (){
$("#btn").click(function() { //кнопка по нажатию которой, переменная i увеличивается на 1
i++;
});
});
var map = new google.maps.Map(document.getElementById('solid-map'), {
center: arrLatLng [i],// элемент массива из адресов.
zoom: 17
});
var marker = new google.maps.Marker({ // маркер 'Московский пр. д.50'
position: myLatLng1,
map: map,
title: 'Московский пр. д.50'
});
var marker2 = new google.maps.Marker({ // маркер 'Заставская улица 30'
position: myLatLng2,
map: map,
title: 'Заставская улица 33'
});
var marker3 = new google.maps.Marker({ // маркер 'ул. Цветочная 10'
position: myLatLng3,
map: map,
title: 'ул. Цветочная 10'
});
}
initMap();
});
Answer the question
In order to leave comments, you need to log in
$('#btn').click(function() {
i = (i + 1) % arrLatLng.length;
map.setCenter(arrLatLng[i]);
});
so what's the point of google maps with its limitations, everything is just for money - drop these hucksters
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question