-2

Sorry for my English, as sought by the latter here in the forum.

Good is simple on principle and what makes me most angry with hehehe.

I have a map of the .js .

var map;
var idInfoBoxAberto;
var infoBox = [];
var markerAgrupado = [];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

function initialize() {

    directionsDisplay = new google.maps.DirectionsRenderer(); 

    var myStyles =[
        {
            featureType: "poi",
            elementType: "labels",
            stylers: [
                  { visibility: "off" }
            ]
        }
    ];

    //características do mapa
    var mapOptions = {
        zoom: 17,
        disableDefaultUI: true, //true = nao mostra os controles padroes(street viewer, botoes: mapa, terreno e satelite) e false para ativar tudo isso.
        zoomControl: true, //true = permite controlar zoom e false o contrario. (sempre deixo ativado para que o cliente se localize melhor...)
        panControl: false, //controle panoramico
        mapTypeControl: false, //escolher tipo de mapa
        scaleControl: false,
        streetViewControl: false, 
        overviewMapControl: false,
        styles: myStyles
    };

    //código dizendo que as características serão atribuídas ao elemento cujo ID no documento seja map-canvas
    map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
    directionsDisplay.setMap(map); // Relacionamos o directionsDisplay com o mapa desejado
    directionsDisplay.setOptions( { suppressMarkers: true } );
    directionsDisplay.setPanel(document.getElementById("trajeto-texto"));

    var icone = './images/maps-fit-me.png'; //código para passar o caminho da imagem do marcador.

    // GEOLOCALIZAÇÃO
    if(navigator.geolocation) 
    {navigator.geolocation.getCurrentPosition(function(position) 
        {

            var posicaoAtual = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);//código que puxar a localização atual do meliante 

            var beachMarker = new google.maps.Marker({
                position: posicaoAtual,
                map: map,
                icon: icone,
                zoom: 17,
            });//código do marcador personalizado.

            map.setCenter(posicaoAtual);        

            function calcRoute(LatAca, LongAca) {
                var start = posicaoAtual;
                var end = LatAca + ',' + LongAca;
                var request = {
                    origin:start,
                    destination:end,
                    travelMode: google.maps.TravelMode.DRIVING
                };

                $( "#trajeto-texto" ).css({'z-index' : '999999999999999999'});

                directionsService.route(request, function(result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(result);
                    }
                });
            }

            function carregarPontos() {

                function abrirInfoBox(id, marker) {
                    if (typeof(idInfoBoxAberto) == 'number' && typeof(infoBox[idInfoBoxAberto]) == 'object') {
                        infoBox[idInfoBoxAberto].close();
                    }

                    infoBox[id].open(map, marker);
                    idInfoBoxAberto = id;
                }

                var icone = './images/altere-maps-fit-me.png'; //código para passar o caminho da imagem do marcador.

                $.getJSON('js/pontos.json', function(pontos) {

                    $.each(pontos, function(index, ponto) {


                        var marker = new google.maps.Marker({
                            position: new google.maps.LatLng(ponto.Latitude, ponto.Longitude),
                            title: ponto.Descricao,
                            map: map,
                            icon: icone
                        });

                        var myWTF =                                 
                                '<div id="iw-container">' +
                                    '<div class="iw-title"><center>' + ponto.long_name +'<br><img src="images/avatar.png" width="60" height="auto"></center></div>' +
                                    '<div class="iw-content">' +
                                        '<table width="100%">'+
                                            '<tr height="30">'+
                                                '<td width="125" align="center">Fechado</td><td width="70"></td><td align="center">10 <img src="images/fitcoin.png" width="15" height="auto"></td>'+
                                            '</tr>'+
                                        '</table>'+
                                        '<p>'+ ponto.endereco+'</p>'+
                                        '<p>'+ ponto.telefones+' | '+ ponto.horario_abertura + ' - ' +ponto.horario_fechamento + '</p>'+
                                        '<p align="center"><button onclick="top.location.href=\'' + 'treinos?a=' + ponto.Id +'\'">Entrar</button><button onclick="top.location.href=\'' + 'academias?id=' + ponto.Id +'\'">Ver perfil</button><button onclick="javascript:calcRoute(' + ponto.Latitude + ',' + ponto.Longitude +');" id="rota">Rota</button></p>'+
                                    '</div>' +
                                '</div>';

                        infoBox[ponto.Id] = new google.maps.InfoWindow({
                            content: myWTF,
                            maxWidth: 350                       
                        });

                        infoBox[ponto.Id].marker = marker;

                        //função que faz o conteúdo da infowindow apareça somente quando você clica em cima do marcador
                        google.maps.event.addListener(marker, 'click', function() {
                            abrirInfoBox(ponto.Id, marker);
                        });

                        //função que faz o conteúdo da infowindow apareça somente quando você clica em cima do marcador
                        $( "#rota" ).click( function() {
                            calcRoute(ponto.Latitude,ponto.Longitude);
                        });

                        // Evento que fecha a infoWindow com click no mapa
                        google.maps.event.addListener(map, 'click', function() {
                            infoBox[ponto.Id].close();
                            $( "#trajeto-texto" ).css({'z-index' : '0'});
                        });

                        //document.getElementById('rota').addEventListener('click', function(){ alert('Testt');});

                        google.maps.event.addListener(infoBox[ponto.Id], 'domready', function() {

                            // Referência ao DIV que agrupa o fundo da infowindow
                            var iwOuter = $('.gm-style-iw');

                            /* Uma vez que o div pretendido está numa posição anterior ao div .gm-style-iw.
                            * Recorremos ao jQuery e criamos uma variável iwBackground,
                            * e aproveitamos a referência já existente do .gm-style-iw para obter o div anterior com .prev().
                            */
                            var iwBackground = iwOuter.prev();

                            // Remover o div da sombra do fundo
                            iwBackground.children(':nth-child(2)').css({'display' : 'none'});

                            // Remover o div de fundo branco
                            iwBackground.children(':nth-child(4)').css({'display' : 'none'});

                            // Desloca a infowindow 115px para a direita
                            iwOuter.parent().parent().css({left: '115px'});

                            // Desloca a sombra da seta a 76px da margem esquerda 
                            iwBackground.children(':nth-child(1)').attr('style', function(i,s){ return s + 'left: 76px !important;'});

                            // Desloca a seta a 76px da margem esquerda 
                            iwBackground.children(':nth-child(3)').attr('style', function(i,s){ return s + 'left: 76px !important;'});

                            // Altera a cor desejada para a sombra da cauda
                            iwBackground.children(':nth-child(3)').find('div').children().css({'box-shadow': 'rgba(178, 178, 178, 0.6) 0px 1px 6px', 'z-index' : '1'});

                            // Referência ao DIV que agrupa os elementos do botão fechar
                            var iwCloseBtn = iwOuter.next();

                            // Aplica o efeito desejado ao botão fechar
                            iwCloseBtn.css({display: 'none', opacity: '1', right: '38px', top: '3px', border: '7px solid #48b5e9', 'border-radius': '13px', 'box-shadow': '0 0 5px #3990B9'});

                        });

                        markers.push(marker);

                    });

                    var markerCluster = new MarkerClusterer(map, markers);

                });

            }

            carregarPontos();

        }, function() 
        {
            handleNoGeolocation(true);
        });
    } else 
        {
            handleNoGeolocation(false);
        }
    //FIM DA GEOLOCALIZAÇÃO

    function handleNoGeolocation(errorFlag)
    {
        if (errorFlag) {
            var content = 'Error: The Geolocation service failed.';
        } else {
            var content = 'Error: Your browser doesn\'t support geolocation.';
        }
    }//código informando erro caso o navegador do usuário não suporte geolocalização

    //SearchBox
    var markers = [];
    var input = (document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var searchBox = new google.maps.places.SearchBox((input));
    google.maps.event.addListener(searchBox, 'places_changed', function() {
        var places = searchBox.getPlaces();

    if (places.length == 0) {
      return;
    }
    for (var i = 0, marker; marker = markers[i]; i++) {
      marker.setMap(null);
    }

    // For each place, get the icon, place name, and location.
    markers = [];
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {
              // Create a marker for each place.
      var searchMarker = new google.maps.Marker({
        map: map,
        //icon: icone,
        zoom: 17,
        title: place.name,
        position: place.geometry.location
      });

      markers.push(searchMarker);

       google.maps.event.addListener(searchMarker, 'click', function() {
                infowindow.open(map,searchMarker);
            });//função que faz o conteúdo da infowindow apareça somente quando você clica em cima do marcador

      bounds.extend(place.geometry.location);
    }

    map.fitBounds(bounds);
  });
    google.maps.event.addListener(map, 'bounds_changed', function() {
    var bounds = map.getBounds();
    searchBox.setBounds(bounds);
     });//Fim da Search Box

    }

    google.maps.event.addDomListener(window, 'load', initialize);

     initialize();

Bookmarks are created from a .json and when clicked the marker he shows a infowindow. Beauty so far so good! Within this infowindow I have a button that loads a current position of the user route function to the clicked marker. So, the function is working perfectly but I can not No Way assigned there in my onclick button.

Function:

function calcRoute(LatAca, LongAca) {
                var start = posicaoAtual;
                var end = LatAca + ',' + LongAca;
                var request = {
                    origin:start,
                    destination:end,
                    travelMode: google.maps.TravelMode.DRIVING
                };

                $( "#trajeto-texto" ).css({'z-index' : '999999999999999999'});

                directionsService.route(request, function(result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(result);
                    }
                });
            }

InfoWindow code that is printed when you clicked the marker:

var myWTF =                                 
   '<div id="iw-container">' +
   '<div class="iw-title"><center>' + ponto.long_name +'<br><img src="images/avatar.png" width="60" height="auto"></center></div>' +
    '<div class="iw-content">' +
    '<table width="100%">'+
    '<tr height="30">'+
    '<td width="125" align="center">Fechado</td><td width="70"></td><td align="center">10 <img src="images/fitcoin.png" width="15" height="auto"></td>'+
    '</tr>'+
    '</table>'+
    '<p>'+ ponto.endereco+'</p>'+
    '<p>'+ ponto.telefones+' | '+ ponto.horario_abertura + ' - ' +ponto.horario_fechamento + '</p>'+
    '<p align="center"><button onclick="top.location.href=\'' + 'treinos?a=' + ponto.Id +'\'">Entrar</button><button onclick="top.location.href=\'' + 'academias?id=' + ponto.Id +'\'">Ver perfil</button><button onclick="javascript:calcRoute(' + ponto.Latitude + ',' + ponto.Longitude +');" id="rota">Rota</button></p>'+
    '</div>' +
    '</div>';

Code Button:

<button onclick="javascript:calcRoute(' + ponto.Latitude + ',' + ponto.Longitude +');" id="rota">Rota</button>

I tried putting the onclick above and also with:

$( "#rota" ).click( function() {
     calcRoute(ponto.Latitude,ponto.Longitude);
});

Please it is very important it is for my TCC :|

4 Answers4

1

The content of the infowindow (including #rota) has not been attached to the document until the domready-event of the infowindow fires, jQuery is not able to find the element.

Add this to your loop where you create the markers:

google.maps.event.addListenerOnce(infoBox[ponto.Id], 'domready', function() {
    var that=this;
    $( "#rota" ).click( function() {
        calcRoute(that.getPosition().lat(),that.getPosition().lng());
    });
});
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • Hello, Dr.Molle! So it makes sense his explanation. At first your code did not work, but with the modification below then worked... "google.maps.event.addListenerOnce(infoBox[ponto.Id], 'domready', function() { $( "#rota" ).click( function() { calcRoute(ponto.Latitude,ponto.Longitude); }); });" Very thanks. o/ – Crystopher Glodzienski Oct 12 '15 at 04:04
1

There are some inconsistencies with your code style. It appears that your convention is not using space between parenthesis, but there are some places that you use spaces, please fix this ASAP as your code is unreadable in its current state. Some examples below:

$( "#trajeto-texto" ).css({'z-index' : '999999999999999999'});

$( "#rota" ).click( function() {
0

Another thing: one good way of improving your code is to wrap it in functions:

function open(tag, attrs) {
  return `<${tag} attrs>`
}
function openDiv(attrs) {
  return open('div', attrs)
}
function close(tag) {
  return `</${tag}>`
}
function closeDiv() {
  return close('div')
}
function closeP() {
  return close('p')
}
var myWTF =                                 
   openDiv('id="iw-container"') +
   openDiv('class="iw-title"')open('center')' + ponto.long_name + open('br')' + open('img', 'src="images/avatar.png" width="60" height="auto"') + close('center')+ close('div') +
    open('div', 'class="iw-content"') +
    open('table', 'width="100%"')+
    open('tr', 'height="30"')+
    open('td', 'width="125" align="center"')Fechado</td><td width="70"></td><td align="center">10 <img src="images/fitcoin.png" width="15" height="auto"></td>'+
    close('tr')+
    close('table')+
    open('p')+ ponto.endereco+
closeP()+

    open('p')+ ponto.telefones+' | '+ 










ponto.horario_abertura + ' - ' +ponto.horario_fechamento + 










closeP()+ openP('align="center"') +
    '<button onclick="top.location.href=\'' +






 'treinos?a=' + ponto.Id +'\'">Entrar</button><button onclick="top.location.href=\'' + 'academias?id=' + ponto.Id +











'\'">Ver perfil</button><button onclick="javascript:calcRoute(' + ponto.Latitude + ',' + 











ponto.Longitude +');" id="rota">Rota</button></p>'+
    closeDiv() +
    closeDiv();
metal bar
  • 522
  • 3
  • 12
-1

You could take a look at how Google Maps API works. Then you should know it is STRICTLY UNCOMPATIBLE WITH JQUERY

metal bar
  • 522
  • 3
  • 12