# Auslesen unterschiedlicher Marker mit Goole Maps API



## fabbrauchthilfe (19. Aug 2008)

Hallo,

habe mit Google Maps API eine Karte erstellt, die die Orte per Array aus einer Datenbank ausließt. 
Das geschieht u. a. über folgende Funktion:


```
function addMarkers(marker, point) {
    if (mArray.length) {
        var bounds = new GLatLngBounds();
        for (n=0 ; n < mArray.length ; n++ ) {
            var mData = mArray[n].split(';');
            var point = new GLatLng(mData[0],mData[1]);
            bounds.extend(point);
            var marker = createMarker(point, mData[2]);
            map.addOverlay(marker);

        }
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); 
    }
}
```

Das ganze funktioniert auch soweit und wird im QuellText folgendermaßen angezeigt:


```
function load() {
    doLoad();
    mArray.push('51.39920565;9.84375000;t;1')
mArray.push('50.43651602;7.98706055;d;2')
mArray.push('50.65294337;9.86022949;b;3')
mArray.push('51.26191485;8.41003418;r;4')
mArray.push('50.54485386;9.27246094;jj;1')
mArray.push('50.34195478;8.43200684;h;4')

usw.
```

Nun will ich je nach Kategorie, das wäre in diesem Fall die letzte Zahl des Arrays 
unterschiedliche Marker anzeigen. Ich hatte mir das ganze dann in etwa so vorgestellt:


```
function addMarkers(marker, point) {
    if (mArray.length) {
        var bounds = new GLatLngBounds();
        for (n=0 ; n < mArray.length ; n++ ) {
            var mData = mArray[n].split(';');
            var point = new GLatLng(mData[0],mData[1]);
            bounds.extend(point);
            
iconcat1 = new GIcon(G_DEFAULT_ICON, "1.png");
iconcat2 = new GIcon(G_DEFAULT_ICON, "2.png");
iconcat3 = new GIcon(G_DEFAULT_ICON, "3.png");
iconcat4 = new GIcon(G_DEFAULT_ICON, "4.png");
            
var catid = mData[3];
    
    if (catid == 1) {
     iconcustom = iconcat1;
    } else if(catid == 2) {
     iconcustom = iconcat2;
    } else if(catid == 3) {
     iconcustom = iconcat3;
    } else {
     iconcustom = iconcat4;
    }

            var marker = createMarker(point, mData[2], iconcustom);
            map.addOverlay(marker);

        }
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); 
    }
```

Leider funktioniert das nicht so, wie ich mir das vorstelle. Ich hoffe ich habe das Problem 
einigermaßen verständlich rübergebracht. Muss dazu sagen, ich bin ein php Anfänger. 
Kann mir hier vielleicht jemand helfen? Wäre echt toll.

Das ganze basiert auf diesem Script:


```
<?


$CONFIG{'hostname'} = 'YOUR_MYSQL_SERVER';
$CONFIG{'user'} = 'YOUR_MYSQL_LOGIN';
$CONFIG{'password'} = 'YOUR_MYSQL_PASSWORD';
$CONFIG{'db'} = 'YOUR_MYSQL_DATABASE';


# WARNING - WARNING - WARNING - WARNING - WARNING - WARNING - WARNING - WARNING
#
# This script will attempt to create the database specified in $CONFIG{'db'}
# and a table called 'geo' in that database.
#
# WARNING - WARNING - WARNING - WARNING - WARNING - WARNING - WARNING - WARNING




$DBH = DB_Connect();

// Make sure the table exists
assertTable();

// define vars
$desc = '';
$lat = '';
$lon = '';

// read POST variables if present
foreach ($_POST as $name => $value) {
    $$name = $value;
}


// If post variables desc,lat and long are not empty then we're inserting
if ($desc &&  $lat &&  $lon) {
    if (is_numeric($lat) && is_numeric($lon) && is_string($desc)) {

        if ($lat < -85 || $lat > 85 || $lon < -180 || $lon > 180) {
            print "You've entered invalid values";
            exit;
        }

        $desc = addslashes(substr($desc,0,200));
        $sql = "insert into geoPoints values ( null , $lat, $lon, '$desc' )";
        $result = mysql_query($sql,$DBH) or DBError("LINE: " .__LINE__. " $sql");
        print "Point inserted
<a href=\"{$_SERVER{'PHP_SELF'}}\">Back to the map</a>\n";
        exit;
    }
}


// Get the javascript defining the points after inserting.
$jsPointsArray = getPointsJS();



$pageHTML = <<<EOH

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Google Maps JavaScript API - PHP/DB Example</title>

    
<script src="/key.js"></script>
<script>
    var scriptTag = '<' + 'script src="http://maps.google.com/maps?file=api&v=2&key=' + myKey + '">'+'<'+'/script>';
    document.write(scriptTag);
</script>

<script type="text/javascript">
var mArray = Array();
var map;
var centerPoint = new GLatLng(40.078071,-101.689453);

function load() {
    doLoad();
    $jsPointsArray
    addMarkers();
}

function doLoad() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.setCenter(centerPoint, 7);
        map.addControl(new GScaleControl());
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        GEvent.addListener(map, 'click', mapClick);

    }
}

function addMarkers() {
    if (mArray.length) {
        var bounds = new GLatLngBounds();
        for (n=0 ; n < mArray.length ; n++ ) {
            var mData = mArray[n].split(';');
            var point = new GLatLng(mData[0],mData[1]);
            bounds.extend(point);
            var marker = createMarker(point, mData[2]);
            map.addOverlay(marker);
        }
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); 
    }
}

function createMarker(point, title) {
    var marker = new GMarker(point,{title:title});
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml('<div style="width:250px;">' + title + '<hr>Lat: ' + point.y + '
Lon: ' + point.x + '</div>');
    });
    return marker;
}

function mapClick(marker, point) {
    if (!marker) {
        oLat = document.getElementById("lat");
        oLat.value = point.y;
        oLon = document.getElementById("lon");
        oLon.value = point.x;
        oDesc = document.getElementById("desc");
        oDesc.value = 'New point';


    }
}



</script>
</head>


<body onload="load()" onunload="GUnload()">

<div id="msg" style="width: 680px; border: 1px solid gray;font: bold 12px verdana;padding:3px;margin:10px;">
Note: Markers from all different visitors are going into the same database and are displayed together.

They could be separated, but I chose to keep it simple. I'll empty the databse once in a while.
</div>

<div id="map" style="width: 700px; height: 500px"></div>


<div id="formDiv">
<table cellspacing="0" cellpadding="2">
<form method="POST">
    <tr>
        <td colspan="2" align="center">Add a marker</td>
    </tr>
    <tr>
        <td>Description</td>
        <td><input id="desc" name="desc"> Example: 'My marker</td>
    </tr>
    <tr>
        <td>Latitude</td>
        <td><input id="lat" name="lat"> Example: 40.0</td>
    </tr>
    <tr>
        <td>Longitude</td>
        <td><input id="lon" name="lon"> Example: -101.5</td>
    </tr>
    <tr>
        <td colspan="2" align="center"><input type="submit" value="Add Point"></td>
    </tr>
    <tr>
        <td colspan="2" align="center">[url="/gm_markers_from_db.php.txt"]View PHP source[/url]</td>
    </tr>
</form>
</table>
</div>




</body>

</html>



EOH;


print $pageHTML;


print DoQueriy('Table contents',"select * from geoPoints order by id");



///////////////////////////// Functions ///////////////////////////////////////

function getPointsJS() {
    global $DBH;
    $sql = "select * from geoPoints";
    $result = mysql_query($sql,$DBH) or DBError("LINE: " .__LINE__. " $sql");
    $nRows = mysql_num_rows($result);

    $javaScript = '';
    if ($nRows) {
        while ($row = mysql_fetch_assoc($result)) {
            $row{'description'} = addslashes($row{'description'});
            $row{'description'} = str_replace(';',',',$row{'description'});
            $javaScript .= "mArray.push('{$row{'lat'}};{$row{'lon'}};{$row{'description'}}')\n";
        }
        
        print "Selected $nRows rows\n";
    }
    else {
        print "No points found in database\n";
    }
    return $javaScript;
}




function assertTable() {
    global $DBH;
    // Create table, if it does not already exist
    $createTableSQL = <<<EOS
    CREATE TABLE IF NOT EXISTS geoPoints (
      id int(11) NOT NULL auto_increment,
      lat decimal(12,8) NOT NULL,
      lon decimal(12,8) NOT NULL,
      description varchar(255) NOT NULL,
      PRIMARY KEY (id)
    ) TYPE=MyISAM;
EOS;

    $sql = $createTableSQL;
    $result = mysql_query($sql,$DBH) or DBError("LINE: " .__LINE__. " $sql");
}


function DBError($sql){
    print "Error: \n" . mysql_error() . "\n";
    print "<hr>\n";
    print "$sql\n";
    print "<hr>\n";
    exit;
}



function DB_Connect() {
    global $CONFIG;
    $DBH = mysql_connect($CONFIG{'hostname'}, $CONFIG{'user'}, $CONFIG{'password'}) or DBError("LINE: " .__LINE__. " Connect");;

    $sql = "create database IF NOT EXISTS {$CONFIG{'db'}}";
    $result = mysql_query($sql,$DBH) or DBError("LINE: " .__LINE__. " $sql");
    
    mysql_select_db($CONFIG{'db'}, $DBH) or DBError("LINE: " .__LINE__. " Select DB");;
    return $DBH;
}



function DoQueriy($title,$sql){
    global $DBH;
    $HTML = '';

    $result = mysql_query($sql,$DBH) or DBError($sql);
    $colCount = mysql_num_fields($result);
    $rowCount = mysql_num_rows($result);

    $HTML .= "<table cellspacing=\"0\" cellpadding=\"0\" border>\n";
    $HTML .= "<tr>\n";
    $HTML .= "    <td colspan=\"$colCount\" style=\"padding:3px;font-weight:bold;text-align:center;\">\n";
    $HTML .= "    $title\n";
    $HTML .= "    </td>\n";
    $HTML .= "</tr>\n";

    if ($rowCount) {
        if ($row = mysql_fetch_assoc($result)) {
            $HTML .= "<tr>\n";
            foreach ($row as $name => $value) {
                $HTML .= "    <td style=\"padding:3px;\">\n";
                $HTML .=        $name;
                $HTML .= "    </td>\n";
            }        
            $HTML .= "</tr>\n";
        }
        
        mysql_data_seek($result,0);
        
        while ($row = mysql_fetch_assoc($result)) {
            $HTML .= "<tr>\n";
            foreach ($row as $name => $value) {
                $HTML .= "    <td style=\"padding:3px;\">\n";
                $HTML .=        $value;
                $HTML .= "    </td>\n";
            }        
            $HTML .= "</tr>\n";
        }
    }
    else {
        $HTML .= "<tr>\n";
        $HTML .= "    <td colspan=\"$colCount\" style=\"padding:3px;font-weight:bold;text-align:center;\">\n";
        $HTML .= "    Empty\n";
        $HTML .= "    </td>\n";
        $HTML .= "</tr>\n";
    }
    
    $HTML .= "</table>\n";
    $HTML .= "
\n";
    return $HTML;

}


?>
```


----------



## Ariol (19. Aug 2008)

java != javascript != php != java


----------



## fabbrauchthilfe (19. Aug 2008)

Ariol hat gesagt.:
			
		

> java != javascript != php != java



und damit willst du mir sagen?


----------



## tfa (19. Aug 2008)

Java ist nicht Javascript! Dies hier ist ein Java-Forum.


----------



## fabbrauchthilfe (20. Aug 2008)

Alles klar, dann versuch ichs mal im javascript Forum..


----------

