Google Maps API v3 - PHP - MYSQL

12,898

Solution 1

If an average/weighted center point is acceptable - you could just average all the latitudes, and average all the longitudes:

$latTotal = 0;
$lngTotal = 0;
foreach ($markers as $marker) {
    $latTotal += $marker['lat'];
    $lngTotal += $marker['lng'];
}

$centerLat = $latTotal/count($markers);
$centerLng = $lngTotal/count($markers);

For the rest of it, there are some good V3 tutorials on Google.

Solution 2

I was using Google Maps v3 a month or two back, but switched to v2 later on. However, I had the same problem as you so I wrote a MarkerManager class for API v3. I can't find the latest version of my class, but I did find a, hopefully, working one. You can get it here.

I have to warn you though - it's not optimazed at all and is not using overlays, so when I tried putting 50+ markers in the manager and toggled the hide/show the class is sloooow... But maybe you can have some success with it.

Usage example:

var map = new google.maps.Map(document.getElementById('MapLayerId'), {
    zoom: 7,
    position: new google.maps.LatLng(latitude, longitude),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker1 = new google.maps.Marker({
    position: new google.maps.LatLng(latitude, longitude),
    map: map
});
var marker2 = new google.maps.Marker({
    position: new google.maps.LatLng(latitude, longitude),
    map: map
});
var manager = new MarkerManager(map, {fitBounds: true});
manager.add(marker1);
manager.add(marker2);
manager.show();

Solution 3

GDownloadUrl in V2 equivalent downloadUrl in GOOGLE MAPS API V3

How to load all the coordinates in database(Mysql or Sql).

var myLatlng = new google.maps.LatLng("37.427770" ,"-122.144841");
var myOptions = {zoom: 15, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP,}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

var url='marker.php?arg1=x&arg2=y...'; 

downloadUrl(url, function(data) {
      var markers = data.documentElement.getElementsByTagName("marker");
      for (var i = 0; i < markers.length; i++) {
        var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
        var marker = new google.maps.Marker({position: latlng, map: map});
       }
});


function createXmlHttpRequest() {
 try {
   if (typeof ActiveXObject != 'undefined') {
     return new ActiveXObject('Microsoft.XMLHTTP');
   } else if (window["XMLHttpRequest"]) {
     return new XMLHttpRequest();
   }
 } catch (e) {
   changeStatus(e);
 }
 return null;
};


function downloadUrl(url, callback) {
     var status = -1;
     var request = createXmlHttpRequest();
     if (!request) {
        return false;
     }     
     request.open('GET', url);     
     request.onreadystatechange = function() {
        if (request.readyState == 4) {
            try {
                status = request.status;
            } catch (e) {
                // Usually indicates request timed out in FF.
            }     
            if (status == 200) {
                 var s=request.responseText;
                 callback( xmlParse(s) ); 
            }
        }
     }  
     try {    
        request.send(null);      
     }catch (e) {    
        changeStatus(e);
     } 
};

function xmlParse(str) {

  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }
  if (typeof DOMParser != 'undefined') {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }
  return createElement('div', null);
}
Share:
12,898
Mickey
Author by

Mickey

Updated on June 04, 2022

Comments

  • Mickey
    Mickey almost 2 years

    GOOGLE MAPS API V3 is what i'm trying to use.

    I have all the coordinates in mysql. I just, for example, need to take 5 listings and put them on a map but I'd like to be able to find the center point based on the multiple coordinates I'd like to display, and the zoom level as well. Yeah know?

    I'm having the time of my life with something that I know is terribly simple, I just can't figure this API out. I'll paypal $20 to anyone who can help me.

    //select * from mysql limit 5
    
    //ok great we got 5 results, great job, format the 5 results so google maps like it, [name,lat,lng] whatever.
    
    //put them on the map and let them be clickable so i can put stuff in the infowindow thing
    
    //make the map adjust to the proper zoom level and center point
    

    UPDATE


    This is what i was looking for, hope this helps others.

    credit to [Chris B] for the common sense math formula for getting the center coord, the sw cord is the lowest lat and lon, and the ne coord is the greatest lat and lon

    sort($lat)&&sort($lon);
    $r['c'] = array_sum($lat)/count($lat).', '.array_sum($lon)/count($lon);
    $r['ne'] = $lat[count($lat)-1].', '.$lon[count($lon)-1];
    $r['sw'] = $lat[0].', '.$lon[0];
    

    var myOptions = {zoom:4,center: new google.maps.LatLng(<?php echo $r['c']; ?>),mapTypeId:google.maps.MapTypeId.ROADMAP}
    var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    <?php foreach($x as $l) echo 'new google.maps.Marker({position:new google.maps.LatLng('.$l['lat'].','.$l['lon'].'),map:map,clickable:true});'; ?>
    map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(<?php echo $r['sw']; ?>),new google.maps.LatLng(<?php echo $r['ne']; ?>)));