I did my searching but unfortunately didnt find relevant solution. I want to do it by using codeigniter google map library. i am following this
link
But it is just showing starting and ending point, it's not creating multiple pins like
This is making multiple pins with polyline but i want routing like:
with multiple pins as shown in polyline map picture.. Is it posible to get multiple directions with multiple pins ??
I tried it but my trick couldn't work. i tried it by using while loop and i incremented the variable before ending point to make my direction like
1st lat, long : starting point
2nd lat, long : ending point
2nd lat, long : starting point
3rd lat, long : ending point
3rd lat, long : starting point
4th lat, long : ending point
But it's only making 1st and last ending point for start and end direction
Here is my controller function
##Load library
$this->load->library('googlemaps');
## Getting data from db
$final_data['final_data'] = $this->Main_manager->getAllEmailLogsById($id);
$email = $final_data['final_data'][0]['email'];
$date = $final_data['final_data'][0]['date'];
$file = 'assets/email_logs/'.$email.'-'.str_replace(' ','-',$date).'.txt';
## Getting lat long data from txt file
$logData = file_get_contents($file);
$logData = json_decode($logData, true);
$marker = array();
$logs = count($logData['logs']);
$config['center'] = $final_data['final_data'][0]['lat'].','. $final_data['final_data'][0]['long'];
$config['zoom'] = 'auto';
$i=0;
while($i<$logs-1):
$config['position'] = $logData['logs'][$i]['lat'].','. $logData['logs'][$i]['long'];
$config['infowindow_content'] = $logs['email'];
$config['animation'] = 'DROP';
$config['draggable'] = FALSE;
$config['directions'] = TRUE;
$config['directionsStart'] = $logData['logs'][$i]['lat'].','. $logData['logs'][$i]['long'];
$i++;
$config['directionsEnd'] = $logData['logs'][$i]['lat'].','. $logData['logs'][$i]['long'];
$config['directionsDivID'] = 'directionsDiv';
endwhile;
## initialize the map
$this->googlemaps->initialize($config);
##create map
$final_data['map'] = $this->googlemaps->create_map();
$this->load->view('administrator/header');
$this->load->view('administrator/view_logs_detail', $final_data);
It seems like you need to use google's DirectionsService.
This service Google map API key to draw routes
Get google key from here login to google account and generate key for your project
Working Demo
HTML
<h1>Google Map direction service</h1>
<div id="map"></div>
CSS
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
JS:
var map;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var locations = [
['Shahrah-e-Faisal, Karachi, Pakistan', 24.8678, 67.0842, 1],
['Tariq Rd, Karachi, Pakistan', 24.8727, 67.0604, 2],
['Service Lane, Karachi, Pakistan', 24.8161, 67.0212, 3]
];
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(24.8678, 67.0842),
});
directionsDisplay.setMap(map);
var infowindow = new google.maps.InfoWindow();
var marker, i;
var request = {
travelMode: google.maps.TravelMode.DRIVING
};
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
if (i == 0) request.origin = marker.getPosition();
else if (i == locations.length - 1) request.destination = marker.getPosition();
else {
if (!request.waypoints) request.waypoints = [];
request.waypoints.push({
location: marker.getPosition(),
stopover: true
});
}
}
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
Related
I'm having difficulty figuring out how to accomplish a specific type of Google Places API request.
I have a zipcode and i want to find out if there are any hospitals within 20 miles of the zipcode
I found the following example maps code and changed the request to hospitals but that didnt perform what i wanted.
So, to summarize, i just want an api request i can convert to PHP that contains an array of available hospitals within 20 miles of a zip code else an empty array. I could also take as an output just a boolean of yes hospitals exist or false otherwise
var sydney = new google.maps.LatLng(-33.867, 151.195);
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(
document.getElementById('map'), {center: sydney, zoom: 15});
var request = {
query: 'hospitals',
fields: ['name', 'geometry'],
};
service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
The Nearby Search or Text Search services would be more appropriate for your use case, since you want to get multiple hospitals and not just one (Find Place returns a single place only).
Try the below code sample which displays hospitals within 20 miles of Pyrmont NSW 2009. Note that location must be a LatLng object, it can't be a zip code, but with Text Search you can add it to your query. Then set the type to hospital.
var map;
var service;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 13
});
var request = {
location: pyrmont,
radius: '32186',
query: '2009',
type: 'hospital'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(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]);
}
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Hope this helps!
I am using google map API integration.I need to get latitude and longitude from particular selected area in that map. In my script based on selected area in google map.
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<p> <div id="map" style="width:980px;height:480px;"></div></p>
In that script, i already create selected area in google map.but i need to get that particular selected area`s longitude and latitude.how to get selected area (cities and countries) value?
You can not get all the cities and countries inside an arbitrary polygon using the Google Maps API. You can get the city and country of a single point using the reverse geocoder using the Google Maps API v3 (or the web service), but an arbitrary polygon would be an infinite number of requests, and would tun into quota and rate limitations. If you have your own source of geographic data (say from geonames) in database that supports geographic queries, you can send the vertices of the polygon to your server and retrieve the locations in that polygon.
hopefully you can help me. I have read a lot of forums regarding this but still cannot get what I wanted. I'm using PHP/MySQL to run my system. I already had a code in JavaScript that will allow the user to add a place and the system can add that place in the Google Map (embedded in my site) as a marker. Now, what I wanted is to add the coordinates of that new place in my database and then my map will just get the markers from the database for adding in the map.
Currently, what I did is to get the latitude and longitude of the added place from the javascript then was able to pass them to my php script within the same file. The latitude and longitude can be added in my database but I do not know now how to go back again to JavaScript so that I can add my markers.
What is the best way to do this? Is/Are there better approaches to solve this?
<?php
$marker = array();
if(isset($_GET['set'])){
$lat = $_GET['lat'];
$long = $_GET['longi'];
$newadd = $_GET['newAdd'];
$connect = mysql_connect("localhost","root","");
mysql_select_db("mapping");
$query=mysql_query("INSERT INTO markers VALUES('','','$newadd','$lat','$long','')");
}
?>
My JavaScript to place markers
function addMarkers(){
var tempMarker;
var tabs = [];
var blueIcon = new GIcon(G_DEFAULT_ICON);
blueIcon.image = "http://maps.google.com/mapfiles/ms/micons/green-dot.png";
// Set up our GMarkerOptions object
markerOptions = { icon:blueIcon };
// for loop get data from db and loop it
tempMarker = new GMarker(tempLatLng,markerOptions);
//if(tabs.length==0){
tabs[ctr] = [new GInfoWindowTab('Greetings','Hi! Welcome'), new GInfoWindowTab('My Info',tempMarker.getLatLng().toString())];
//}
tabInfoWindow(tempMarker,tabs, ctr);
markerArray.push(tempMarker);
displayMarkers();
}
}
Thanks!
Using jquery you can post the data in an ajax request and continue adding the markers in the success handler.
var location = {lat:56, lng:67, name:"my_place"};
$.ajax({
url: "save_place.php",
data: location,
dataType:"json",
success: function(response){
if(response.success){
// add marker to map here
}else{
alert("Error adding location to database");
}
},
error:function(){
alert("Error in connecting to server");
}
});
EDIT:
From your comments, I understand what you need is this one:
<?php
$lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
$long = isset($_GET['longi']) ? $_GET['longi'] : 0;
$newadd = isset($_GET['newAdd']) ? $_GET['newAdd'] : "";
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<style type='text/css'>
#map {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<div id="map"></div>
<script type='text/javascript'>//<![CDATA[
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(55, 11),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function addMarker(lat, lng, newAdd) {
alert(" Adding marker " + lat + "," + lng);
this.lat = lat;
this.long = lng;
var location = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
position: location,
title: name,
map: map,
draggable: true
});
map.setCenter(location);
}
<?php
echo "addMarker($lat, $long, '$newadd')";
?>
</script>
</body>
</html>
url : http://<domain>/test.php?lat=40.735812&longi=-74.001389&newAdd=
Well what I do is have a endpoint on the PHP side that I can ask for the markers. Then when my map has loaded I will make a call to get them and then add them on:
$.post('/server/getMarkers',{},function(markers) {
for(var i=0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(marker[i].latitude, marker[i].longitude),
id:marker[i].id
});
google.maps.event.addListener(marker, "click", function() {
//request data for this.id to show in info window if needed
});
}
});
The getMarkers method on the PHP side could look something like this
public function getMarkers() {
/* fetch an array of markers details from the db by any means... */
$markers = getMarkersFromDB();
foreach ($markers as $key=> $marker) {
$payload[$key]['latitude'] = $marker->latitude;
$payload[$key]['longitude'] = $marker->longitude;
$payload[$key]['id'] = $marker->id;
}
echo json_encode($payload);
}
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);
});
});
}
);
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