kretan kretan - 6 months ago 69
SQL Question

Geocoding by extracting location from MySQL via PHP

I have written the following PHP script to get the value from MySQL database:

<?php
$user="root";
$password="password";
$dbh = new PDO("mysql:host=localhost;dbname=muzicmap", $user, $password);

$sql = "SELECT DISTINCT (
`name`
) AS `name` , `id` , `location` , `background` , `genre` , `current_members` , `website` , `image` , `lonlat`
FROM `artist`
WHERE `location` LIKE '%Los Angeles%'
LIMIT 10
";

$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);

//Or if you need to edit/manipulate the result before output
foreach ($result as $row){
$return[]=array('id' => $row['id'],'name'=>$row['name'],'location'=> $row['location'],'background' => $row['background'], 'genre' => $row['genre'],'current_members'=>$row['current_members'],'website' => $row['website']);
}
$dbh = null;

header('Content-type: application/json');
echo json_encode($return);
?>


Now I have made a page in which I want to achieve 3 things:
1. Geocode the location in the location field of my json.
2. Put markers on google maps.
3. Make a drawable type object after doing this all.

So I wrote the following:

markers= []
var geocoder;

function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(40.2859268188,-75.9843826294)
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.CIRCLE,
]
},
circleOptions: {
fillColor: '#FFFF00',
fillOpacity: 0,
strokeWeight: 1,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
var IDs=[];
for(var k in markers){
if(google.maps.geometry.spherical
.computeDistanceBetween(circle.getCenter(),markers[k].getPosition())
<=circle.getRadius()){
IDs.push(k);
}
}
});

$(function ()
{
$.ajax({
url: 'jsonTest.php', //the script to call to get data
data: "",
dataType: 'json',
success: function(data)
{
adMarker(map, data);
}
});
});
}

function adMarker(map,json1){
geocoder= new google.maps.Geocoder();
for (var i = 0; i < (json1.length); i++) {
geocoder.geocode({'address':json1[i]['location']},function(results,status){
if (status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: json1[i]['names'],
zIndex: json1[i]['id']
});
markers.push(marker);
}else {
alert("Something wrong");
}

});
}

}

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


I am not getting the desired result where the markers are put on the map after geocoding. When I debug it I see that the code snipet which is supposed to geocode and create the marker is not run in the for iteration. Why is that? I am new to javascript I would really appreciate all the help fixing this.

The error in the debugger though,says:

InvalidValueError: setZIndex: not a number

Answer

I solved the problem.

Because there is an asynchronous call in the adMarker(). I made a function so that copies of that function are made on each for iteration as the asynchronous call will run only after the iteration is complete. This way all the iteration with copies will run. Updated code:

function adMarker(map,json1){

        geocoder= new google.maps.Geocoder();
        for (var i = 0; i < (json1.length); i++) {
        abc(i, json1, map);
            }

      }
      function abc (index, json1, map){ 
        var current_index = index;
        geocoder.geocode({'address':json1[index]['location']},function(results,status){

                if (status == google.maps.GeocoderStatus.OK){
                    var marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map,
                    title: json1[index]['names'],
                    zIndex: parseInt(json1[index]['id']) 
                    });
                    markers.push(marker);
                }else {
                    alert("Something wrong");
                }               
        });
        }