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);
?>
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.
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.
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.
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
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);
}
I made this using prototypes, the code is much more cleaner. An example (supose you are using jquery):
Create 3 scripts:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With