Google Maps load issues on PHP page - php

I'm connecting a Google Map to a MySQL database to list distributors all over the world, and I seem to be having a few issues.
Sometimes the page itself will not load at all in Firefox (v4 on Mac). It's temperamental on my machine (FF v3.6 Mac) and a Windows machine (FF v4 Win 7), ok in Safari/Opera, doesn't load at all in IE 9 (Win 7). Not sure if it's a network issue or code.
Load time is pretty slow. Might be because the map covers the whole page (will create a square block to place it in).
The URL of the page is here and I used the code from Sean Feeney's page.
The code I have is:
<script src="http://maps.google.com/maps?file=api&v=2&key=<I entered my key here>" type="text/javascript"></script>
<body onUnload="GUnload()">
<div id="map" style="position:absolute;top:0px;bottom:0px;left:0;right:0;"></div>
</body>
<script type="text/javascript">
//<![CDATA[
var map;
var latlngbounds;
if (GBrowserIsCompatible()) {
function createMarker(point, address) {
var marker = new GMarker(point);
var html = address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
function extendBounding(point) {
latlngbounds.extend(point);
var zoom = map.getBoundsZoomLevel(latlngbounds);
if (zoom < 10) {
zoom = 12;
}
map.setCenter(latlngbounds.getCenter(), zoom);
}
}
map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
latlngbounds = new GLatLngBounds();
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var address = markers[i].getAttribute("address");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, address);
map.addOverlay(marker);
extendBounding(point);
}
});
}
//]]>
</script>
The code that gets the data is the same as the example.
Any ideas as to why it doesn't always load in the browsers, and why it seems to take a while to load?
Thanks,
Adrian

Ideally you should wrap the code that loads the map inside a document ready or window load event.
I notice that your code is not nested properly inside the GBrowserIsCompatible() block so please fix that.
As far as I remember, Google maps API v2 requires you to call the setCenter() method before doing any operations on the map. So to begin with, set the center to (0, 0) immediately after creating the map.
I notice that you're downloading XML data before you add markers to the map. You must take into account the time taken by the server to serve the XML data. If you've called the setCenter() before downloading the XML, the map will display while the XML downloads asynchronously.
Inside the code that handles the XML data: when you add a marker, do not call setCenter() immediately. Doing so will cause the function to be called 1000 times if you have 1000 markers in your XML. Instead, just call latlngbounds.extend(point). Once you have iterated the loop, calculate the zoom/center and call setCenter(). This way you will end up calling this function only twice.
Edit
I've figured out what the problem is. The genxml.php randomly returns the string Google Geo error 620 occurred which cannot be parsed as XML which raises JavaScript errors and no markers are shown. Better have a look at the code of that file and see why this happens randomly. On other times when that file actually returns valid XML, the markers appear as expected.

It appears Google recently tightened geocoding requests. If you send 10 too fast, it cuts you off with 620 error. The solution they recommend is adding a dynamic timer. Other stackoverflow posts suggested a 0.25 second static timer was good enough, but I've found Google's recommendation of using a while loop that increments the timer value as needed works better. For example:
// Initialize delay in geocode speed
public $delay = 0;
public function lookup(arguments)
{
$geocode_pending = true;
while ($geocode_pending) {
$search = //address string to search;
$response = $this->performRequest($search, 'xml');
$xml = new SimpleXMLElement($response);
$status = (int) $xml->Response->Status->code;
switch ($status) {
case self::G_GEO_SUCCESS:
require_once('placemark.php');
$placemarks = array();
foreach ($xml->Response->Placemark as $placemark)
$placemarks[] = Placemark::FromSimpleXml($placemark);
$geocode_pending = false;
return $placemarks;
case self::G_GEO_TOO_MANY_QUERIES:
$delay += 100000;
case self::G_GEO_UNKNOWN_ADDRESS:
case self::G_GEO_UNAVAILABLE_ADDRESS:
return array();
default:
throw new Exception(sprintf('Google Geo error %d occurred', $status));
}
usleep($delay);
}
}

You can run your map code with window.load after everything is loaded:
jQuery(document).ready(function initAutocomplete() {
var p_lag=$('#longitude').val();
var p_lat=$('#latitude').val();
if(p_lat==''){
var p_lat=20.593684;
}
if(p_lag==''){
var p_lag=78.96288000000004 ;
}
var myLatLng = {lat: p_lat,lng: p_lag};
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: myLatLng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: myLatLng,
draggable: true,
map: map,
title: 'Map'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
//Click event for getting lat lng
google.maps.event.addListener(map, 'click', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
google.maps.event.addListener(marker, 'dragend', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
/*markers.forEach(function (marker) {
marker.setMap(null);
});*/
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
$('#latitude').val(place.geometry.location.lat());
$('#longitude').val(place.geometry.location.lng());
marker.setPosition(place.geometry.location);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
});
}
);

Related

Javascript Ajax page starts responding slow after some time?

I have a JavaScript ajax page, which fires an ajax request (using setInterval function) every 20 seconds and gets response in JSON format. In the page; using JSON response I'm displaying the markers on Google map (using API v3) and updating them every 20 seconds based on the location received from ajax response. I'm displaying an infoWindow on click event of marker.
I am using PHP as server side scripting, which generates my ajax response by doing some DB calls.
Everything works fine when I open the page. But slowly the page starts responding slow. I mean when I click on the marker or on related text, page takes a significant time to locate the marker, to load the map and to open the infoWindow. And the slowness of page increases as the time passes. If I refresh the page, again everything starts working fine.
The page don't even show a single error at any point of time and I must add that the auto updation of location of markers works fine throughout the life of the page.
I've tried everything which I found on forums. Like, I've moved to json response from an xml(dom) response. I've tried changing the XMLHttpRequest methods, as the GET requests have tendency to auto cache the data. But nothing helped me. I am completely clueless, what is wrong, what I am doing in my code.
Here is my JavaScript code:
<script type="text/javascript">
var map;
var contentString = "";
var infoWindow = new google.maps.InfoWindow({content: contentString});
var url = "genAjaxResponse.php?id=<?php echo $id; ?>";
var marker;
var gmarkers = new Array();
var icon;
var lastClickedMarker;
var stImgId;
var customIcons = {
Moving: {
icon: 'icons/abc.png'
},
Idle: {
icon: 'icons/xyz.png'
},
Parked: {
icon: 'icons/pqr.png'
},
Alert: {
icon: 'icons/wxy.png'
}
};
function load() { // to be called on onload event of body
map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
center:new google.maps.LatLng(15.570128,78.957092)
});
calldownloadUrl(url,map,infoWindow);
directionsDisplay = new google.maps.DirectionsRenderer();
}
function calldownloadUrl(url,map,infoWindow) {
downloadUrl(url,displayMarker,map,infoWindow);
}
function displayMarker(data,map,infoWindow) {
function generateTriggerCallback(object, eventType) {
return function() {
google.maps.event.trigger(object, eventType);
};
}
var namearr = Array();
var json = data.responseText;
var vehicles = eval ("(" + json + ")");
var i = 0;
for (var veh in vehicles)
{
var tag = vehicles[veh];
var veh_no = tag["veh_no"];
var is_stale = tag["is_stale"];
var ignition_off = tag["ignition_off"];
var speed = tag["speed"];
var lat = tag["lat"];
var lng = tag["lng"];
var time = tag["time_stamp"];
var address = tag["address"];
var point = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng));
var type;
var status;
stImgId = i+1;
if(ignition_off == 0 && speed > 3) {
type = "Moving";
status = type + "(" + speed + " Kmph)";
document.getElementById("img"+stImgId).src = "icons/greenalert2.png";
}
else {
if(ignition_off == 1) {
type = "Parked";
status = type;
document.getElementById("img"+stImgId).src = "icons/greyalert2.png";
}
else {
type = "Idle";
status = type;
document.getElementById("img"+stImgId).src = "icons/yellowalert2.png";
}
}
if(is_stale == 1) {
type = "Alert";
status = type;
document.getElementById("img"+stImgId).src = "icons/redalert2.png";
}
infoWindow.close();
var icon = customIcons[type] || {};
if(typeof gmarkers[i] != 'undefined') {
gmarkers[i].setPosition(point);
gmarkers[i].setIcon(icon.icon);
if(gmarkers[i].id == lastClickedMarker) {
if(map.getBounds().contains(gmarkers[i].getPosition()) === false)
map.setCenter(gmarkers[i].getPosition());
}
}
else
{
gmarkers[i] = new google.maps.Marker({
id: i,
position: point,
icon: icon.icon,
title: veh_no,
map: map
});
}
var html = "<span><p><b>"+veh_no +"</b></p> <p>Address: "+address+"<br />Status: "+status+"<br />Time: "+time+"</p></span>";
namearr[i] = "<span><p><b>"+veh_no +"</b></p> <p>Address: "+address+"<br />Status: "+status+"<br />Time: "+time+"</p></span>";
// -- bind click event to texts (vehicle nos) -- //
var textclick = document.getElementById(i);
textclick.onclick = generateTriggerCallback(gmarkers[i],"click");
// -- bind click event to markers -- //
bindinfoWindow(gmarkers[i], map, infoWindow, namearr[i], icon);
i++;
}
}
function bindinfoWindow(marker, map, infoWindow, html, icon) {
google.maps.event.addListener(marker, 'click', function() {
lastClickedMarker = marker.id;
map.setCenter(marker.getPosition());
if(map.zoom < 15)
map.setZoom(15);
marker.setIcon(icon.icon);
marker.setZIndex(google.maps.Marker.MAX_ZINDEX + 1);
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback, map, infoWindow) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, map, infoWindow, request.status);
}
};
request.open('GET', url, true);
request.send();
}
function doNothing() {}
window.setInterval(function() {calldownloadUrl(url,map,infoWindow)},20000);
</script>
I've a similar app and I've also ran into similar behavior.
In my case, I've been updating an array of markers every 30 secs (for each marker: location, icon, content of a listener).
Firstly, I have stopped creating a new marker each update, I thought that setting markers[id].setMap(null); and creating new one will be OK, that CG will handle this.
Then I've changed the code to only update markers position, icon and listener, like this:
this.markers[id].setPosition(new google.maps.LatLng(lat, lng));
this.markers[id].setIcon(this.updateFlags(status, id));
google.maps.event.addListener(this.markers[id], 'mouseover', function () {
infoWindow.setContent(text);
infoWindow.open(this.map, this);
});
google.maps.event.addListener(this.markers[id], 'click', function () {
devices.selectDevice(index);
});
This produced much less consumed memory, but still...
Finally I've edited code like this:
this.markers[id].setPosition(new google.maps.LatLng(lat, lng));
this.markers[id].setIcon(this.updateFlags(status, id));
google.maps.event.clearListeners(this.markers[id], 'mouseover');
google.maps.event.clearListeners(this.markers[id], 'click');
google.maps.event.addListener(this.markers[id], 'mouseover', function () {
infoWindow.setContent(text);
infoWindow.open(this.map, this);
});
google.maps.event.addListener(this.markers[id], 'click', function () {
devices.selectDevice(index);
});
I've tested it in Chrome Developer Tools (F12) -> Profiler and Take Heap Snapshot. And you will see if it grows too fast.
So in your case it would mean adding this line as the first line of function bindinfoWindow():
google.maps.event.clearListeners(marker, 'click');
I think you need to empty the gmarkers array each time you calling that ajax request, or reset the i variable before you processing the received data. In this way you are not adding all the new markers to the previous ones, which seems is the bottleneck in your code.
P.S. I didn't test your code. I'm just guessing.

Marker issue with the google tutorial "Using PHP/MySQL with Google Maps"

I am trying to make a database of locations to fill out a FAFSA for my non profit and put them up on a google map with a custom marker image but cant seem to get the markers to show up.
here is the php to create the xml:
<?php
require("mapdbinfo.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect ("Localhost", $username, $password);
if (!$connection) { die("Not connected : " . mysql_error());}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) { die("Can\'t use db : " . mysql_error());}
$query = "SELECT * FROM locations WHERE 1";
$result = mysql_query($query);
if (!$result) { die("Invalid query: " . mysql_error());}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = mysql_fetch_assoc($result)){
// Add to XML document node
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("type", $row['type']);
$newnode->setAttribute("date", $row['date']);
$newnode->setAttribute("cord", $row['cord']);
$newnode->setAttribute("cord_info", $row['cord_info']);
}
echo $dom->saveXML();
?>
here is the java script:
function load() {
var location_icon = new google.maps.MarkerImage('images/FAFSA_Logo_icon.png');
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(35.105305, -106.628014),
zoom: 9,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
}
downloadUrl("mapmysql.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address + "<b> Cordinator </b>" + cord + cord_info;
var icon = location_icon;
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url,callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
I can't figure out why they markers aren't showing up. the file is located in that images folder but, there are to many places that this could be going wrong for me to effectively troubleshoot with my current knowledge. I pretty much copied and pasted the code from the google example except for adding some fields to pull from the xml and added a custom icon image.
Any ideas on how to get these markers to show up? the map shows up with the center and zoom I have selected but not the markers.
I think I may see a few problems (I'll get to them in a minute), but first I'm going to try to offer some more general debugging advice -
Testing someone's code which relies on a server-side code is pretty tricky, even if it's your own. The first thing I would do in a case like this is create a generic xml file to parse, and include it in the page. Then, hopefully you can tell if the bug is occurring in the map rendering portion of the code if something goes wrong. If it works, then you can narrow the bug down to being either on the server, or in the code you're using to get it from the server.
Next, I would try to put the xml file on the server as-is, and see if the client-side file download is working. I suspect this is where you'd notice at least one error. Right now, your map rendering depends on two separate steps: the "load" function, which initializes the map; and a call to the "downloadURL" function, which you're relying on to get the marker data.
The problem is in how you structured the calls. The "map" variable you created in "load" is local to "load" itself; you cannot access it outside of it. There are two ways you can fix this particular problem: you can turn map into a global variable, or add all code that manipulates map within "load". If you wish to do the former, you just do this:
var map;
function load() {
var location_icon = new google.maps.MarkerImage('images/FAFSA_Logo_icon.png');
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(35.105305, -106.628014),
zoom: 9,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
}
This adds "map" to the global scope, allowing it to be used outside of "load".
However, there's still a problem with doing this as-is: this won't guarantee that "load" has initialized the map by the time "downloadURL" starts manipulating it. There's a chance that it will attempt to add "markers" to "map" before "load" has had a chance to create map in the first place. Fortunately, this can be solved by putting the "downloadURL" call within "load", like so:
function load() {
var location_icon = new google.maps.MarkerImage('images/FAFSA_Logo_icon.png');
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(35.105305, -106.628014),
zoom: 9,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("mapmysql.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for(var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address + "<b> Cordinator </b>" + cord + cord_info;
var icon = location_icon;
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
This ensures that markers will only be added to the map after the map has been created, and that they'll have access to map in the first place.
Check the javascript console for errors
Check the xml. Point your browser at it, see if it thinks it is valid.
Use a debugger (or just add an alert) in your map where it parses the marker xml, check that the length of the markers variable that is being processed by this for loop is correct:
for (var i = 0; i < markers.length; i++) {
One of the above should point to the issue. If not, post a link to your live map and someone can figure it out.

Distance between a searched address and nearest existing placemark on a google maps api v3

I'm developing a web page with a Google Maps API v3. I currently have a functional map and search bar. I need to be able to display the distance from a searched address to the nearest placemark on one of the KML files on the map. How can I do this?
Here is the code for the page:
<script type="text/javascript">
var geocoder;
var map;
var marker;
var layers = [];
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (41, -73.4);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
marker = new google.maps.Marker({map:map});
layers[0] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/South-and-North-County-Trailway.kml',
{preserveViewport: true});
layers[1] = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml',
{preserveViewport: true});
layers[2] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/NWS%20Radar%20Images.kmz',
{preserveViewport: true});
for (var i = 0; i < layers.length; i++) {
layers[i].setMap(map);
}
}
function codeAddress () {
var address = document.getElementById ("address").value;
geocoder.geocode ( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results [0].geometry.location);
marker.setPosition(results [0].geometry.location);
map.setZoom(14);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function toggleLayer(i) {
if(layers[i].getMap() === null) {
layers[i].setMap(map);
}
else {
layers[i].setMap(null);}
}
</script>
You cannot access the data in KML layers like that
https://developers.google.com/maps/documentation/javascript/layers#KMLLayers
Because KML may include a large number of features, you may not access
feature data from the KmlLayer object directly. Instead, as features
are displayed, they are rendered to look like clickable Maps API
overlays.
Instead you can process the XML and add markers manually, then use the geometry library and computeDistanceBetween() to get the distance. I usually multiply the distance by some number to account for turns (The distance formula gets a straight line distance). I believe around 1.2 was the most accurate.

How to locate places nearby to my custom markers

I have a webapp that creates markers on a google map and I'm wondering if there is some way to locate place nearby my custom markers so users can see what is around them.
Thank you in advance,
Robert
The Places Libraryapi-doc provides the information you seek. You load the library by adding the libraries=places parameter to the URL that loads the Google Map, as shown here:
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false">
</script>
And then you request data about places using code similar to this, copied from the Place Search Requests section of the Developer's Guide, which will search for stores within 500 meters of the point defined in the variable pyrmont:
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
types: ['store']
};
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}

Google Maps API v3 - PHP - MYSQL

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']; ?>)));
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.
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();
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);
}
Have you checked out the official google map PHP/Mysql tutorial?
http://code.google.com/apis/maps/articles/phpsqlajax.html
Try this algorithm for finding the centroid of a polygon:
http://tog.acm.org/resources/GraphicsGems/gemsiv/centroid.c

Categories