Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Markers not displaying on google map, but no errors in console

Have been pulling my hair out about this for a while: trying to use json to get lat/lng values from my database and then use these values to output markers onto a google map. Currently the map is displaying without the markers and there are no errors in the console. Any help would be greatly appreciated!

 <script type="text/javascript">
       var map = null;

       function addMarker(lat,lng) {
             marker = new google.maps.Marker({
             position: new google.maps.LatLng(lat,lng),
             map: map,
           });
     }


      function initialize() {
      var mapOptions = {
      center: {lat: 54.872128, lng: - 6.284874},
      zoom: 13
     };
    map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

   $(document).ready(function(){

   $.getJSON('MarkersController.php', function(data){


         var locations = JSON.parse(data);

         for(var i =0; i<locations.length; i++){
               addMarker(locations['lat'], locations['lng']);
      }
});
});


}

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

The php script for retrieving from mysql:

<?php

include('DB_INFO.php');

// Opens a connection to a MySQL server.

$connection = mysqli_connect($server, $username, $password);

if (!$connection) {
    die('Not connected : ' . mysqli_error());
}
// Sets the active MySQL database.
$db_selected = mysqli_select_db($database, $connection);

if (!$db_selected) {
    die('Can\'t use db : ' . mysqli_error());
}

// Selects all the rows in the markers table.
$query = 'SELECT * FROM tester';
$result = mysqli_query($query);

if (!$result) {
    die('Invalid query: '. mysqli_error());
}

$list = array();
while ($row = mysqli_fetch_assoc($result)) {
    $list[] = $row;
}
header('Content-Type: application/json');
echo json_encode($list);
?>
like image 977
fst104 Avatar asked Aug 18 '15 11:08

fst104


People also ask

Why labels are not showing in Google Maps?

First off, ensure that you have zoomed in enough. Some street names will not show on the map unless you zoom in enough. This is because Google maps do not allow the street labels to overlap so the space for the street name can only be enough if you zoom right in.

How do you refresh a marker on Google Maps?

maps. Animation. DROP, to your markers, so that you can see when they are reloaded, and a reload markers button to call the reload function.

Why isn't my Google Maps API working?

There are a several reasons why your google maps may not be working, the most common issue being no Google Map API key set or set incorrectly. To use the Google Maps JavaScript API, you must register your app project on the Google Cloud Platform Console and get a Google API key which you can add to your app.


3 Answers

If you have a collection of marker i think you should use this way iteranting on the collection and assignd the i element :

for(var i =0; i<locations.length; i++){
  addMarker(locations[i].lat, locations[i].lng);
}

proof of concept fiddle

like image 107
ScaisEdge Avatar answered Oct 15 '22 16:10

ScaisEdge


You may give it a try by changing to below.

while ($row = mysqli_fetch_assoc($result)) {
    //Assuming "lat" is column name in tester table. Please change it if required.
    $lat= $rows['lat'];

    //Assuming "lng" is column name in tester table. Please change it if required.
    $lng= $rows['lng'];

    $list[] = array('lat' => $lat, 'lng' => $lng);
}
like image 45
Haris Avatar answered Oct 15 '22 14:10

Haris


I made this using prototypes, the code is much more cleaner. An example (supose you are using jquery):

Create 3 scripts:

  1. Map script
  2. JSONParser script
  3. Main script

First Create the prototype functions for work with google maps:

 var MapUtil = (function($) {

    var mapProp = {
        center: new google.maps.LatLng(-38.4529181, -63.5989206),
        zoom: 4,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    /**
     * @returns
     * Maps options for create a google map
     */
    function getMapProperties() {
        return mapProp;
    }

    /**
     * Create simple marker
     * @param lat
     * Latitude for the marker
     * @param lng
     * Longitude for the marker
     * @param myMap
     * Actual map
     * @returns
     * Return a new google map marker
     */
     function simpleMarker(lat, lng, myMap) {
         var marker = new google.maps.Marker({
             //add the marker options
             position: new google.maps.LatLng(lat, lng),
             draggable:true,
             animation: google.maps.Animation.DROP,
             map: myMap,
         });

        return marker;
     }

    return {
        getMapProperties: getMapProperties,
        simpleMarker: simpleMarker,
    };

})(jQuery);

Then create the JSONParser for transform the JSON to javascript objects:

var JSONParser = (function($){

    /**
     * @return An array with the markers parsed
     */
    function getMarkers(json) {
        var markers = [];
        for (int i = 0; i < json.length; i++) {
            markers.push({json[i].lat,json[i].lng});
        }

        return markers;
    }

    return {
        getMarkers : getMarkers,
    };

})(jQuery);

And you main script:

$(document).ready(function() {
    var myMap = null;

    //add the map to the page
    google.maps.event.addDomListener(window, 'load', initialize);

    /**
     * Init Google Maps
     */
    function initialize() {
        var map=new google.maps.Map(document.getElementById("googleMap"), 
                MapUtil.getMapProperties());
        myMap = map;

        createMarkers();
    }

    function createMarkers() {
        //retrieve the information
        $.ajax({             
            type: 'post',
            url: 'MarkersController.php',
            data: {},
            success: function (data) {
                var json= $.parseJSON(data);
                var markers = JSONParser.getMarkers(json);

                for (var i = 0; i < markers.length; i++) {
                    MapUtil.simpleMarker(marker[i].lat, marker[i].lng, myMap);
                }
            }
        });
    }
});

Then add the scripts to the html in this order:

<script src="...path.../map-utils.js"></script>
<script src="...path.../json-pareser.js"></script>
<script src="...path.../main.js"></script>

For other functionality about the map or json add extra methods!

like image 34
user1977204 Avatar answered Oct 15 '22 14:10

user1977204