Creating Points in Google Maps with PHP Data

Asked

Viewed 6,053 times

2

What I need

I need that through PHP I receive locations and can mark them as points in Google Maps.

What I did

I created a part in Ajax to call the PHP script that does the query and returns the json. It receives the data. He’s adding the dots on the map, but when I click on one of them he doesn’t open the box with the information.

JS

var map;
var idInfoBoxAberto;
var infoBox = [];
var markers = [];
var localizacao = [];
//var markerPonto = new google.maps.Marker({});
var markerPonto;
var contador = 0;
var l = 0;
var contentString;
var infowindow = new google.maps.InfoWindow({
    content: contentString,
    maxWidth: 300
});

/*Método que inicia configurações iniciados do mapa*/
function initialize() {
    var latlng = new google.maps.LatLng(-23.5514565,-46.6224739);

    var options = {
        zoom: 6,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("mapa"), options);

    /*Novo parte - adiciona ponteiro geolocalizador(de acordo com as coordenadas informadas em 'latlng'*/
    geocoder = new google.maps.Geocoder();

    marker = new google.maps.Marker({
        map: map,
        draggable: true,
    });

    marker.setPosition(latlng);

    /*Parte de loop com banco de dados*/
    $.ajax({
        url : 'verificaAjax.php',
        success : function(msg){
            if (msg.status == 0) {
                msg.errorMsg.forEach(ShowResults);
                //JSON.parse(msg.errorMsg).forEach(ShowResults);

            }
        },
        error:function (xhr, ajaxOptions, thrownError) {
            alert("Erro no Processamento dos Dados. Entre em contato com o setor de Tecnologia e informe a mensagem abaixo:\n"+xhr.responseText);
        }

    });

}

// Função para retornar os valores
function ShowResults(value, index, ar) {
    contentString = '<h2>'+value['razao_social']+'</h2>';

    localizacao.push({
        nome: value['razao_social'],
        latlng: new google.maps.LatLng(value['latitude'],value['longitude'])
    });


    /*
    markerPonto.position(localizacao[l].latlng);
    markerPonto.icon('img/marcador.png');
    markerPonto.map(map);
    markerPonto.title(localizacao[l].nome);
    */


    markerPonto = new google.maps.Marker({
        position: localizacao[l].latlng,
        icon: 'img/marcador.png',
        map: map,
        title: localizacao[l].nome
    });

    google.maps.event.addListener(markerPonto, 'click', function() {
        infowindow.open(map,v);
    });

    ++l;


}

PHP

<?php
    header('Content-type: application/json;');
    require('bd.php');

    $bancoDeDados = new Bd();

    //Armazena o resultado
    $mensagemResultado = array("status" => 1, "errorMsg" => array());

    //Obtem todos os resultados de pontos de entrega
    $resultadoConsulta = $bancoDeDados->selectPontos();
    if (count($resultadoConsulta) > 0) {
        $mensagemResultado["status"] = 0;
        $mensagemResultado["errorMsg"] = array_merge($mensagemResultado["errorMsg"],$resultadoConsulta);
    }

    echo json_encode($mensagemResultado);
  • I think you’re forgetting to parse of this data coming from PHP. You have already tested JSON.parse(msg.errorMsg).forEach(ShowResults); ? or use type: 'json' in the AJAX configuration?

  • Do points change places over time? If they are fixed, you do not need Ajax, just generate the map source by PHP itself.

  • @Sergio I have another solution where I implemented the sending of the form data by json passing to a php (as well as in this code) and returning to JS. I even took it as a basis, and I didn’t have to do any data conversion.

  • @Bacco Yes. They can be modified in the future.

1 answer

2


I’m assuming that:

  • On the map, only one box should remain open, the infowindow (I mean, by clicking another marker closes the infowindow and re-opens in the new location)

  • The social reason can be very long

I made the following changes to the map to show the box when a marker is clicked.

I took the initial definition of content of the box because it will be replaced after.

var infowindow = new google.maps.InfoWindow({
    // content: contentString,   
    maxWidth: 300
});

Add the keyword var before the markerPonto (without this var, the markerPonto turns global variable), and we want a separate for each addListener.

var markerPonto = new google.maps.Marker({
    ...

Finally, for each listener, you need to create a new scope to remember the value of the Social Reason. For this I use an anonymous function. (functions create new scopes in Javascript). Without using it, would appear the same value, the last, in all boxes.

  (function(contentString) {
    google.maps.event.addListener(markerPonto, 'click', function() {
      infowindow.setContent('<div style="line-height: 1.35;">' + contentString + '</div>');
      infowindow.open(map, markerPonto);
    });
  })(contentString);

The addition of line-height is to avoid a problem I found while testing. Without it, a scrollbar appeared inside the box.

I faked the part about pulling data by simply calling ShowResults :

ShowResults({'razao_social': 'Carlos',
           'latitude': -23.44,
           'longitude': -43.22,
          });

See demonstration on Jsfiddle

  • Great! You don’t know how grateful you are.

  • One thing I would like to do, is when accumulated an amount of points in a very close region, a counter was displayed. Here is an example - http://www.princiweb.com.br/demos/google-maps-api-v3-criando-mapa-customizable/

  • @Allanramos Have you tried to follow in the footsteps of this blog? I noticed that his link goes to Markerclusterer (without Plus), but that Markerclusterer Plus seems to be better. This is the link to Plus http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.1.2/

  • I saw it and I used it. I’m sorry. So I ran a test and I put in 2,500 dots, but by the proximity of them, the map was slow and they weren’t clustered properly. I will now look at this link you passed. Thank you !

  • @Allanramos I did some tests and noticed that it is better to create your array of points first, and then create Markerclusterer, joining the markers at once. I demonstrate the alternative, which is to use addMarker one at a time (in the Showresults function). So, when I drag the map I see it for a fraction of a second according to the markers. Even so for 3000 points, I did not notice slow. Please follow the link: http://jsfiddle.net/d49j2gLt/ It may be that you are creating a new Markercluster for each point, this may cause slowness. We only need one Markercluster object and use addMarker if necessary.

Browser other questions tagged

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