Use Javascript/Google Maps database addresses

Asked

Viewed 3,110 times

5

I have in a database the following columns: customer name, active or inactive, address and coordinates lat and lng.

I need to develop a PHP application that will display green markers in Google Maps for active clients, and red inactive ones for each marker with its respective location.

I already have a static solution, need to know how the solution would look in PHP, how PHP will treat the data and run in Javascript.

Here’s the code:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1., user-scalable=no" />
        <style type="text/css">
            html {
                height: 1%
            }
            body {
                height: 1%;
                margin:;
                padding:
            }
            #map_canvas {
                height: 1%
            }
            #info {
                position: absolute;
                z-index: 333;
                width: 19px;
                height: auto;
                float: right !important;
                top: 5px;
                right:;
                margin-right: 3px;
                border: 3px solid #f3f3f3;
                border-radius: 5px;
                padding:8px;
                background: #fff;
            }
            #info span {
                position: absolute;
                margin-top: 3px;
                margin-left: 1px;
            }
        </style>
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=&sensor=TRUE">

        </script>
        <script type="text/javascript">
            function initialize() {
                var mapOptions = {
                    center: new google.maps.LatLng(-26.91597, -48.67952),
                    zoom: 7,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                    //mapTypeId: google.maps.MapTypeId.SATELLITE,
                    //mapTypeId: google.maps.MapTypeId.HYBRID
                    //mapTypeId: google.maps.MapTypeId.TERRAIN
                };
                var map = new google.maps.Map(document.getElementById("map_canvas"),
                mapOptions);


                //Esta aplicação pega o ponto atual e cria um marcador com um ícone da empresa
                /*var ponto = new google.maps.LatLng(-26.91597, -48.67952);
        var marker = new google.maps.Marker({
            position:ponto,
            map:map,
            title: 'Itajaí',
            draggable: true,
            icon: 'ativo2.png'
        })*/

                var localizacao = [];
                localizacao.push({
                    nome: "Joinville",
                    latlng: new google.maps.LatLng(-26.2784142, -48.8563719)
                });
                localizacao.push({
                    nome: "Balneário Camboriú",
                    latlng: new google.maps.LatLng(-27.8161, -48.626631)
                });
                localizacao.push({
                    nome: "Rio Grande do Sul",
                    latlng: new google.maps.LatLng(-3.4163414, -53.6677564)
                });
                localizacao.push({
                    nome: "Florianópolis",
                    latlng: new google.maps.LatLng(-27.6142358, -48.4828248)
                });
                localizacao.push({
                    nome: "Brusque",
                    latlng: new google.maps.LatLng(-27.912233, -48.8892335)
                });

                for (var i = ; i < localizacao.length; i++) {
                    var marker = new google.maps.Marker({
                        position: localizacao[i].latlng,
                        icon: 'ativo2.png',
                        map: map,
                        title: localizacao[i].nome
                    });
                }

                var localizacao = [];
                //localizacao.push({nome:"Penha", latlng: new google.maps.LatLng(-26.795582,-48.6325339)});
                //localizacao.push({nome:"Blumenau", latlng: new google.maps.LatLng(-26.8727952,-49.167329)});
                //localizacao.push({nome:"Navegantes", latlng: new google.maps.LatLng(-26.8631691,-48.6771822)});
                //localizacao.push({nome:"Ilhota", latlng: new google.maps.LatLng(-26.8654127,-48.8724734)});
                localizacao.push({
                    nome: "Gaspar",
                    latlng: new google.maps.LatLng(-26.9263595, -48.9522665)
                });

                for (var i = ; i < localizacao.length; i++) {
                    var marker = new google.maps.Marker({
                        position: localizacao[i].latlng,
                        icon: 'inativo2.png',
                        map: map,
                        title: localizacao[i].nome
                    });
                }

                //Esta aplicação pega as cooordenadas lng e lat e mostra no HTML
                /*google.maps.event.addListener(map, "bounds_changed", function(){
            var bounds = map.getBounds();
            var NE = bounds.getNorthEast();
            var SW = bounds.getSouthWest();
            var strHTML = "North East: " + NE.lat() + ", " + NE.lng() + "<br />";
            strHTML += "South West: " + SW.lat() + ", " + SW.lng();
            document.getElementById("info").innerHTML = strHTML;
        })*/
            }
            window.onload = initialize;
        </script>
    </head>

    <body>
        <div id="map_canvas" style="width:1%; height:1%"></div>
        <div id="info">
            <img src="ativo2.png" width="25" height="24"><span>Clientes Ativos: 5</span>
            <br />
            <img src="inativo2.png" width="25" height="24"><span>Clientes Inativos: 1</span>

        </div>
    </body>

</html>
  • What have you done? What is your doubt? This doubt is very wide.

  • 2

    Welcome to Sopt. This question will probably be closed because it is too wide. Study https://developers.google.com/maps/? hl=en. Then try to do something, if you get into difficulties or specific doubts edit this question to ask for help.

  • 2

    Complementing the link given by @Earendul, I suggest starting here: https://developers.google.com/maps/documentation/javascript/tutorial?hl=pt-br

  • 2

    Igor: can generate a PHP object to be read by javascript with each group. So you can with javascript open the bookmarks on the map. If you have server-side difficulties (PHP) ask here with the specific problem. The same for if you have problem on the client side (javascript). Asking about both is difficult to answer concisely.

  • 1

    @Sergio Sorry, I did it for the moderator’s tool and then I realized.

1 answer

3

The solution you already have in Javascript is a great start. What’s missing is generating this array of objects on the server side.

It could simply do so (code to be printed inside the tag script) next to a database search:

<?php
$objetoMarcadores = 'var localizacao = [';
while($marcador = mysqli_fetch_assoc($resultados)){
    $objetoMarcadores.='{nome: '.$marcador["nome"].', latlng: '.$marcador["latlng"].' }';
}
$objetoMarcadores.='];';
$objetoMarcadores = trim($objetoMarcadores , ","); // para tirar a ultima virgula
echo $objetoMarcadores;
?>

That cycle while will create an array of objects that you can use as you had in javascript. Having a string can join more content with .=. So it starts the string before the while, fills it with objects inside the while and at the end closes the array. In other words, javascript will be loaded with this already present content. The aspect will be something like:

var localizacao = [{ nome: "Florianópolis", latlng: .... etc ];

The possible problem here is how to convert latlang for Googlemaps to use. It depends a little on how you have it stored in the database. But having an array in Javascript can always do .map() and create a new array with the objects with the correct property.

Type:

localizacao = localizacao.map(function(obj){ 
    return {
        nome: obj.nome, 
        latlng: new google.maps.LatLng(obj.latlng)
    };
});
  • Thank you for your answer, the solution you proposed seems to be ideal. I will only have to do two select and while, one to bring active customers and their location in the same way for inactive.

  • @Igorsilva can add one more property to the object, estado and so only need 1 Select. Or else make two arrays one localizacaoAtivos and another localizacaoInativos

  • 1

    Sergio, I think that this way that you mentioned would be the correct solution, I will be the code and post here the result being positive or not.

  • @Igorsilva got it working?

  • Sergio, I haven’t tried to implement the application with the back end yet because I might be working on geolocation. The system will pick up the coordinates, and on another map that will serve as a monitoring, will show a marker with the location, updating it according to the individual’s displacement. Would you know to tell me if there are any examples of how to work this way?

  • @Igorsilva update is in real time, by time interval or each time the page loads?

Show 1 more comment

Browser other questions tagged

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