Google Maps - Set Zoom user

Asked

Viewed 388 times

1

I have this code down with the Google Maps API using various places defined within Javascript. My problem is that I have more stores to add and they’re spread all over the state, so I want when the user opens the page, take your location and put it inside the page, so he can see the stores nearby.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCPFf086alCsl076VnHe4ap3nEgCx4hZvU&libraries=places"></script>
<section class="breadcrumb">
    <div class="container">
        <ul>
            <li><a href=""><i class="fa fa-home"></i></a>
            <li>
                <a href="{{asset('lojas')}}" target="_self">
                    Lojas                   </a>
            </li>
        </ul>
    </div>
</section>

<div class="container">
    <h1 class="v1">Encontre a loja mais perto de você</h1>
</div>

<section class="conteudo-texto">
    <div class="container">
        <div id="map" style="height: 400px; width: 100%;"> <!-- onde o mapa vai aparecer-->
        </div>
        <script type="text/javascript">
            var locations = [ // definição de todas as lojas
                ['<div>'+
                '<h2 class="firstHeading"><b>Design Persianas<b/></h2>'+
                '<div id="bodyContent">'+
                '<p>Rua Hermes Pacheco, 1117 <br/> Hípica <br/> Porto Alegre <br/> 51 - 3352.4277</p>'+
                '</div>'+
                '</div>', -30.1669899,-51.2017468,17],

                ['<div id="content">'+
                '<div>'+
                '</div>'+
                '<h2 class="firstHeading"><b>Maison Decor<b/></h2>'+
                '<div id="bodyContent">'+
                '<p>Av. Pereira Passos, 1152 <br/> Cristal <br/> Porto Alegre <br/> 51 - 3265.4800</p>'+
                '</div>'+
                '</div>', -30.1034039,-51.2551846,17],

                ['<div>'+
                '<h2 class="firstHeading"><b>Soleil Persianas<b/></h2>'+
                '<div id="bodyContent">'+
                '<p>Rua Selso Maffessoni, 70 <br/> Aberta dos Morros <br/> Porto Alegre <br/> 51 - 3246.7685</p>'+
                '</div>'+
                '</div>', -30.1354365,-51.2165426,17],

                ['<div>'+
                '<h2 class="firstHeading"><b>Decorações Berti<b/></h2>'+
                '<div id="bodyContent">'+
                '<p>Rua Lima e Silva, 837 <br/> Cidade Baixa <br/> Porto Alegre <br/> 51 - 3226.6468</p>'+
                '</div>'+
                '</div>', -30.0399515,-51.2218371,17],

                ['<div>'+
                '<h2 class="firstHeading"><b>Cortinas Berti<b/></h2>'+
                '<div id="bodyContent">'+
                '<p>Av. Cristiano Fischer, 776 <br/> Bom Jesus <br/> Porto Alegre <br/> 51 - 3334.6881</p>'+
                '</div>'+
                '</div>', -30.0463707,-51.1741466,17],

                ['<div>'+
                '<h2 class="firstHeading"><b>Claudia Cortinas<b/></h2>'+
                '<div id="bodyContent">'+
                '<p>Av. Protasio Alves, 2038 <br/> Petropolis <br/> Porto Alegre <br/> 51 - 3024.4792</p>'+
                '</div>'+
                '</div>', -30.042944,-51.1909027,17],

                ['<div>'+
                '<h2 class="firstHeading"><b>Porto Windows <b/></h2>'+
                '<div id="bodyContent">'+
                '<p>Rua Silva Jardim, 78 <br/> Auxiliadora <br/> Porto Alegre <br/> 51 - 3028.7788</p>'+
                '</div>'+
                '</div>', -30.0228021,-51.1925731,17],

                ['<div>'+
                '<h2 class="firstHeading"><b>Casa Bonita<b/></h2>'+
                '<div id="bodyContent">'+
                '<p>Rua Eudoro Berlink, 888 <br/> Auxiliadora <br/> Porto Alegre <br/> 51 - 3332.5627</p>'+
                '</div>'+
                '</div>', -30.0239334,-51.1907752,17],

                ['<div>'+
                '<h2 class="firstHeading"><b>Casa das Redes<b/></h2>'+
                '<div id="bodyContent">'+
                '<p>Rua Felipe Camarão, 469 loja 104 <br/> Bom Fim <br/> Porto Alegre <br/> 51 - 3312.1824</p>'+
                '</div>'+
                '</div>', -30.033244,-51.2120567,17],

                ['<div>'+
                '<h2 class="firstHeading"><b>Casa Rezende<b/></h2>'+
                '<div id="bodyContent">'+
                '<p>Rua Daltro Filho, 1130 <br/> Boa Vista <br/> Alegrete <br/> 55 - 3422.3386</p>'+
                '</div>'+
                '</div>', -29.7878098,-55.8041166,17],

            ];

            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 10, // zoom padrão
                center: new google.maps.LatLng(-30.0575488,-51.247716,9.46), // inicio do zoom - AQUI QUE PRECISO MUDAR
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            var infowindow = new google.maps.InfoWindow(); //mostra as informações escritas

            var marker, i;

            for (i = 0; i < locations.length; i++) { // lista todos os lugares
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                    map: map
                });

                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        infowindow.setContent(locations[i][0]);
                        infowindow.open(map, marker);
                    }
                })(marker, i));
            }
        </script>        </div>
</section>

1 answer

1


Use the Browser Location service

The browser will ask the user to allow you to use the service and if they allow it, it will trigger the function and change the position of the map to its location. There’s no way you can do it right on the map startup.

In your code change to look like this:

<script type="text/javascript">

    // ... seus dados dos markers ....

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10, // zoom padrão
        center: new google.maps.LatLng(-30.0575488,-51.247716,9.46), // inicio do zoom - AQUI QUE PRECISO MUDAR
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow(); //mostra as informações escritas

    // tentar ativar a geolocalização do browser

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            map.setCenter(pos);

        }, function() {
            handleLocationError(true, infowindow, map.getCenter());
        });
    } else {
        handleLocationError(false, infowindow, map.getCenter());
    }

    function handleLocationError (browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Erro: O serviço de Geolocalização falhou.' :
                              'Erro: Seu browser não suporta geolocalização.');
        infoWindow.open(map);
    }

    // ... adiciona seus markers ....

</script>   

Help from Google Maps Developers : https://developers.google.com/maps/documentation/javascript/geolocation

  • Thank you very much, it worked, but there’s something else. It always says that the Service has failed, I’m suspecting that I need an Https link for this, is that correct? You can see in http://persilux.escritoriomovel.com/shops

  • Try debugging to see if it failed because of the browser or the service. I’ve had problems using localhost as well.

  • I opened your site and the error message in the script says that the method it calls needs to come from HTTPS address. If you can’t find an alternative, put https on your website, you have free options Let’s Encrypt

  • I found that response in the OS where the guy uses an external server to search for the location when HTTPS fails. It seems to work and the problem is that your site will make a call to an unknown service and maybe this could open a security gap since your site would be without http, but it is an alternative.

  • I’ll try it with letsencrypt, I already use it in other applications. Strange that if I try to use it on the localhost that Google provides, it works. https://developers.google.com/maps/documentation/javascript/geolocation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.