Creating Points in Google Maps with PHP Data


What I need

I need to be able to receive locations from within PHP and tag them as points on Google Maps.

What I did

I created a part in Ajax to call the script in PHP that does the query and returns the json. He receives the data. He is adding the points on the map, but when I click on any of them he does not open the box with the information.


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,


    /*Parte de loop com banco de dados*/
        url : 'verificaAjax.php',
        success : function(msg){
            if (msg.status == 0) {

        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>';

        nome: value['razao_social'],
        latlng: new google.maps.LatLng(value['latitude'],value['longitude'])


    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() {,v);




    header('Content-type: application/json;');

    $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);
asked by anonymous 03.12.2014 / 19:49

1 answer


I'm assuming that:

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

  • The business name can be very long.

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

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

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

Add the keyword var before the markerPonto (without this var, the marker becomes global variable), and we want a separate one 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, it would appear the same value, the last one, in all the boxes.

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

Adding line-height is to avoid a problem I encountered while testing. Without it, a scrollbar would appear inside the box.

I've simulated the data pulling part simply by calling ShowResults :

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

See JSFiddle demo

11.12.2014 / 00:42