I'm trying to add a link in my Google Map marker window. But my code only shows the marker and the window but it does not show the link.
I'm trying to add the link in this line:
$marker['infowindow_content'] = "<?php echo anchor('index/get_by_id/$id',{$row->subject} on {$row->address}')?>";
when the link is clicked it go to some function of my index controller.
but why the link is not appearing in the window.
controller:
function index()
{
if(empty($_POST)){
$this->load->helper('form');
$this->googlemaps->initialize();
$marker = array();
//$this->main_model->get_map();
if($result = $this->main_model->ll()){
//var_dump($result);
foreach($result->result() as $row) {
//var_dump($row);
//$data[]=$row;
$marker['position'] = "{$row->lat},{$row->lng}";
$id=$row->id;
$marker['infowindow_content'] = "<?php echo anchor('index/get_by_id/$id',{$row->subject} on {$row->address}')?>";
$marker['animation'] = 'DROP';
//var_dump($marker['position ']);
$this->googlemaps->add_marker($marker);
}
}
//$this->googlemaps->add_marker($marker);
$data['map'] = $this->googlemaps->create_map();
$data['list'] = $this->main_model->getdata();
$this->load->view('main_view',$data);
}
}
Model:
public function ll($id = '')
{
$sql = $this->db->get('info');
if ($sql->num_rows () >0) {
return $sql;
}
else{
return null;
}
}
The generated html from my code(the map part only):
<script type="text/javascript">
//<![CDATA[
var map; // Global declaration of the map
var iw = new google.maps.InfoWindow(); // Global declaration of the infowindow
var lat_longs = new Array();
var markers = new Array();
function initialize() {
var myLatlng = new google.maps.LatLng(65.84815, 24.14670);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var myLatlng = new google.maps.LatLng(65.85051,24.14529);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_0 = createMarker(markerOptions);
marker_0.set("content", "<?php echo anchor('index/get_by_id/1',street problem on something home)?>");
google.maps.event.addListener(marker_0, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
var myLatlng = new google.maps.LatLng(65.84931,24.14555);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_1 = createMarker(markerOptions);
marker_1.set("content", "<?php echo anchor('index/get_by_id/2',hello on 11 some)?>");
google.maps.event.addListener(marker_1, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
var myLatlng = new google.maps.LatLng(65.84858,24.14160);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_2 = createMarker(markerOptions);
marker_2.set("content", "<?php echo anchor('index/get_by_id/3',problem street on 78900 street)?>");
google.maps.event.addListener(marker_2, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
var myLatlng = new google.maps.LatLng(65.85000,24.14773);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_3 = createMarker(markerOptions);
marker_3.set("content", "<?php echo anchor('index/get_by_id/4',gulshan street on 11 gulshan)?>");
google.maps.event.addListener(marker_3, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
var myLatlng = new google.maps.LatLng(65.84620,24.14593);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_4 = createMarker(markerOptions);
marker_4.set("content", "<?php echo anchor('index/get_by_id/5',broken road on banani)?>");
google.maps.event.addListener(marker_4, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
var myLatlng = new google.maps.LatLng(65.84961,24.15164);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_5 = createMarker(markerOptions);
marker_5.set("content", "<?php echo anchor('index/get_by_id/6',no lamp on arbritary)?>");
google.maps.event.addListener(marker_5, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
}
function createMarker(markerOptions) {
var marker = new google.maps.Marker(markerOptions);
markers.push(marker);
lat_longs.push(marker.getPosition());
return marker;
}
window.onload = initialize;
//]]>
The issue is with this line:
$marker['infowindow_content'] = "<?php echo anchor('index/get_by_id/$id',{$row->subject} on {$row->address}')?>";
The content for an InfoWindow is a string containing the actual HTML code. In your case, the <?php block is ignored as you can see in the generated HTML:
marker_0.set("content", "<?php echo anchor('index/get_by_id/1',street problem on something home)?>");
It has to be :
marker_0.set("content", "<a href='index/get_by_id/1'>street problem on something home</a>");
Try this:
<?php
$subject = $row->subject;
$address = $row_>address;
?>
var index = '<?php echo $id; ?>';
var subject = '<?php echo $subject; ?>';
var address = '<?php echo $address; ?>';
$marker['infowindow_content'] = "<a href='index/get_by_id/" + index + "'>" + subject + " on " + address + "</a>";
Related
I am wondering how I might add variables from my php code into a javascript code.
For example, my query results in vertreklat, vertreklong, aankomstlat, aankomstlong
My javascript code:
echo "<script src='http://maps.googleapis.com/maps/api/js?sensor=false'></script>
<script>
/* ***** Start CustomMarker ***** */
function CustomMarker(latlng, map, marker_id, hovercard) {
this.latlng_ = latlng;
this.marker_id = marker_id;
this.hovercard_content = hovercard;
this.setMap(map);
}
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.draw = function() {
var me = this;
var div = this.div_;
if (!div) {
div = this.div_ = document.createElement('DIV');
div.id=me.marker_id;
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
}
var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
if (point) {
div.className = 'map-marker show-hovercard';
div.style.left = (point.x-6) + 'px';
div.style.top = (point.y-23) + 'px';
$(div).attr('data-hovercard-content', me.hovercard_content);
}
};
CustomMarker.prototype.remove = function() {
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
CustomMarker.prototype.getPosition = function() {
return this.latlng_;
};
/* ***** End CustomMarker ***** */
function initialize() {
var markers = [];
var bounds = new google.maps.LatLngBounds();
var myOptions = {
center: new google.maps.LatLng(20, 20),
zoom: 2,
mapTypeId: google.maps.MapTypeId.TERRAIN,
panControl: false,
streetViewControl: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
pos = new google.maps.LatLng(vertreklat, vertreklong);
overlay = new CustomMarker(pos, map, 'marker_KMSP', 'some name');
overlay.setMap(map);
bounds.extend(pos);
pos = new google.maps.LatLng(aankomstlat, aankomstlong);
overlay = new CustomMarker(pos, map, 'marker_RJAA', 'some name');
overlay.setMap(map);
bounds.extend(pos);
var flightPath = new google.maps.Polyline({path: [new
google.maps.LatLng(vertreklat, vertreklong),new google.maps.LatLng(aankomstlat,
aankomstlong)], strokeColor: '#ffffff', strokeOpacity: 0.7, strokeWeight: 2, geodesic:
true });
flightPath.setMap(map);
map.fitBounds(bounds);google.maps.event.addListener(map, 'zoom_changed',
function() {
if(map.getZoom()<2) {
map.setZoom(2);
}
});
}
$(document).ready(function() {
initialize();
});
</script>";
All of the data that needs to come from my query goes within this part of the script:
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
pos = new google.maps.LatLng(**vertreklat, vertreklong**);
overlay = new CustomMarker(pos, map, 'marker_KMSP', 'some name');
overlay.setMap(map);
bounds.extend(pos);
pos = new google.maps.LatLng(**aankomstlat, aankomstlong**);
overlay = new CustomMarker(pos, map, 'marker_RJAA', 'some name');
overlay.setMap(map);
bounds.extend(pos);
var flightPath = new google.maps.Polyline({path: [new
google.maps.LatLng(**vertreklat, vertreklong**),new google.maps.LatLng(**aankomstlat,
aankomstlong**)], strokeColor: '#ffffff', strokeOpacity: 0.7, strokeWeight: 2, geodesic:
true });
flightPath.setMap(map);
But I am confused as to how to accomplish this task....
Try this:
var flightPath = new google.maps.Polyline({path: [new
google.maps.LatLng(".$row['vertreklat'].",".$row['vertreklong']."),new google.maps.LatLng(".$row['aankomstlat'].",".$row['aankomstlong'].")], strokeColor: '#ffffff', strokeOpacity: 0.7, strokeWeight: 2, geodesic:
true });
Since you started the echo wqith double quotes you can use them again to break the string and concatenate with dot .. By the way should your PHP variables not have a $ ?
For such long blocks of output, instead of echo return back literal output with ?>. Then insert small blocks of <?php ... ?> where you need to echo variables.
?>
<script src='http://maps.googleapis.com/maps/api/js?sensor=false'></script>
<script>
/* ***** Start CustomMarker ***** */
function CustomMarker(latlng, map, marker_id, hovercard) {
this.latlng_ = latlng;
this.marker_id = marker_id;
this.hovercard_content = hovercard;
this.setMap(map);
}
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.draw = function() {
var me = this;
var div = this.div_;
if (!div) {
div = this.div_ = document.createElement('DIV');
div.id=me.marker_id;
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
}
var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
if (point) {
div.className = 'map-marker show-hovercard';
div.style.left = (point.x-6) + 'px';
div.style.top = (point.y-23) + 'px';
$(div).attr('data-hovercard-content', me.hovercard_content);
}
};
CustomMarker.prototype.remove = function() {
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
CustomMarker.prototype.getPosition = function() {
return this.latlng_;
};
/* ***** End CustomMarker ***** */
function initialize() {
var markers = [];
var bounds = new google.maps.LatLngBounds();
var myOptions = {
center: new google.maps.LatLng(20, 20),
zoom: 2,
mapTypeId: google.maps.MapTypeId.TERRAIN,
panControl: false,
streetViewControl: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
pos = new google.maps.LatLng(<?php echo $vertreklat ?>, <?php echo $vertreklong ?>);
overlay = new CustomMarker(pos, map, 'marker_KMSP', 'some name');
overlay.setMap(map);
bounds.extend(pos);
pos = new google.maps.LatLng(<?php echo $aankomstlat ?>, <?php echo $aankomstlong ?>);
overlay = new CustomMarker(pos, map, 'marker_RJAA', 'some name');
overlay.setMap(map);
bounds.extend(pos);
var flightPath = new google.maps.Polyline({path: [new
google.maps.LatLng(vertreklat, vertreklong),new google.maps.LatLng(<?php echo $aankomstlat ?>, <?php echo $aankomstlong ?>)], strokeColor: '#ffffff', strokeOpacity: 0.7, strokeWeight: 2, geodesic:
true });
flightPath.setMap(map);
map.fitBounds(bounds);google.maps.event.addListener(map, 'zoom_changed',
function() {
if(map.getZoom()<2) {
map.setZoom(2);
}
});
}
$(document).ready(function() {
initialize();
});
</script>
You can use short echo open tag:
<script>
var foo = <?=$foo?>;
console.log(foo);
</script>
or use AJAX
I am having error of OVER_QUERY_LIMIT in using google maps api v3. I want to add markers from database by geocoding. If I use limit in sql query then the markers are shown, if I increase the limit greater than 10 then its showing the error.
<?php
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('dbname') or die(mysql_error());
$result = mysql_query("SELECT * FROM deal WHERE cityID=44 LIMIT 10") or die(mysql_error());
$count = 0;
echo mysql_num_rows($result);
$row = mysql_fetch_array($result);
?>
<script type="text/javascript">
var geocoder;
var map;
//var address;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.052234,-118.243685);
var address = "<?php echo $row['address']; ?>";
//address = '3655 South Durango, Las Vegas, NV 89147';
//alert(address);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
while($row = mysql_fetch_array($result)){
?>
geocoder.geocode( { 'address': "<?php echo $row['address']; ?>"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
"<h1 id='firstHeading' class='firstHeading'><?php echo $row['businessName']; ?></h1>"+
'<div id="bodyContent">'+
"<p><?php echo $row['longDesc']; ?></p>"+
'<p>Attribution: Uluru, <a href="#">'+
'Click To See</a> '+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
<?php sleep(1); ?>
} else {
alert("Geocode was not successful for the following reason: " + status);
//setTimeout("wait = true", 2000);
}
});
<?php } ?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You can't geocode more than 2500 locations per day with free version.
Based on my memories, you also have to wait approximatively 0.5 seconds between two geocods, so you must delay you script ; else you'll be blocked.
I am trying to place markers where the cities in a mySQL database are. The page loads but it shows "map div" where the map should load. I am not sure what is wrong. Thank you for taking a look and trying to help!
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
//create an array of latitudes, longitudes, and city names
var markers = [
<?php
//orgnize fans by city
$query = "SELECT city, state, COUNT(*) fans FROM users GROUP BY city ORDER BY fans DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
//pulls the city, state code from the database and stores it as a string in $address
$address = urlencode('"' . $row['city'] . ", " . $row['state'] . '"');
$googleApi = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false';
$json = file_get_contents(sprintf($googleApi, $address));
$resultObject = json_decode($json);
$location = $resultObject->results[0]->geometry->location;
$lat = $location->lat;
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$lng.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
}
?>
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.name;
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your Current City'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
When I open the html, I call initialize and make the canvas:
<body onload="initialize()">
<div id="map_canvas" style="width: 1100px; height: 450px;">map div</div>
I am trying to make an array of latitudes and longitudes using cities that I have in a mySQL database. This is what I have so far. I am trying to set up the array variable in javascript, and echo out the fields inside. The "markers" array is read to make markers appear on the google map at the desired locations:
EDIT: Here is the entire script
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
var markers = [
<?php
//orgnize fans by city
$query = "SELECT city, state, COUNT(*) fans FROM users GROUP BY city ORDER BY fans DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
//pulls the city, state code from the database and stores it as a string in $address
$address = urlencode('"' . $row['city'] . ", " . $row['state'] . '"');
$googleApi = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false';
$json = file_get_contents(sprintf($googleApi, $address));
$resultObject = json_decode($json);
$location = $resultObject->results[0]->geometry->location;
$lat = $location->lat;
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$lng.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
}
?>
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.name;
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your Current City'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
When I open the html, I call initialize and make the canvas:
<body onload="initialize()">
<div id="map_canvas" style="width: 1100px; height: 450px;">map div</div>
You have a typo: sometimes you use long, at other times lng.
in the code segment:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});}
while earlier you use
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$long.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
In effect, your echo statement, which should be producing longitudes in your array, is referencing a non-initialized variable, $long. Fix that and you should be good to go. In other words, change
$lng = $location->lng;
to
$long = $location->lng;
(or change your echo statement...)
My earlier answer dealt with the typo. I think there's a fundamental issue with "how to draw maps with the google API". The following code snippet (from google JavaScript API shows an example of using overlays (which is what a marker is):
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP, }
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!" });
// To add the marker to the map, call setMap();
marker.setMap(map);
Several of these steps appear to be missing from your code - maybe you didn't show them, or maybe you didn't realize you needed them?
EDIT: even after you posted your full code, I still don't see certain things I would expect.
Here are one thing you can try for sure: call the google API before referencing it: add this line
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"> </script>
right below <head>, before your <script>
Fixing just this, and taking out a bunch of "superfluous" (for the purpose of "getting a map with a pin") lines, allowed me to create a simple file that can render a map of New York, NY with one marker on it. The source code can be found at http://www.floris.us/SO/maptest.php.txt . From there, you can add more stuff back in...
Further edit: with the lessons learnt, I made http://www.floris.us/SO/maptestFull.php which has most of the functionality you were looking for (not the DB lookup, which I don't have, obviously). Once again, source code is copied in .php.txt file so you can look at it. Slightly messy (from trying to turn things on/off) - you will have to look closely to see all the changes I made.
I started with https://developers.google.com/maps/articles/phpsqlajax_v3 and am using
https://developers.google.com/maps/articles/phpsqlsearch_v3 to try to dynamically filter the content from a mysql DB and update my markers based on the returned results.
My php returns a valid xml file so no worries there. I'm just not sure what I'm doing wrong for the clearing and creating the new markers from the new query.
The load() function gives me a nice new map with markers on it, but the form doesn't seem to do anything. I even tried just have the form button call clearLocations() and nothing happens. The screen kinda blinks but all the points stay there.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Property Sales</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var markersArr = [];
var map;
var infoWindow;
function updateMap(){
var maxbid = document.getElementById('maxbid').value;
var minbid = document.getElementById('minbid').value;
var salestatus = document.getElementById('salestatus').value;
var saledate = document.getElementById('saledate').value;
infoWindow = new google.maps.InfoWindow;
var queryString = "phpsqlajax_genxml3dynamic.php?maxbid=" + maxbid + "&minbid=" + minbid + "&salestatus=" + salestatus + "&saledate=" + saledate;
//var queryString = "phpsqlajax_genxml3dynamic.php?maxbid=" + maxbid + "&minbid=" + minbid;
queryString="phpsqlajax_genxml3dynamic.php?maxbid=340000&minbid=0&salestatus=*&saledate=*";
downloadUrl( queryString, function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
clearLocations();
for (var i = 0; i < markers.length; i++) {
var SaleDate = markers[i].getAttribute("SaleDate");
var CaseNumber = markers[i].getAttribute("CaseNumber");
var Address = markers[i].getAttribute("Address");
var ZipCode = markers[i].getAttribute("ZipCode");
var Plaintiff = markers[i].getAttribute("Plaintiff");
var Defendant = markers[i].getAttribute("Defendant");
var Attorney = markers[i].getAttribute("Attorney");
var SoldTo = markers[i].getAttribute("SoldTo");
var PID = markers[i].getAttribute("PID");
var Appraisal = markers[i].getAttribute("Appraisal");
var MinBid = markers[i].getAttribute("MinBid");
var SaleAmt = markers[i].getAttribute("SaleAmt");
var SaleStatus = markers[i].getAttribute("SaleStatus");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("Latitude")),
parseFloat(markers[i].getAttribute("Longitude"))
);
var info = "<b>Sale Date:" + SaleDate +"<br/>Address:"+ Address+"<br/>Sale Amount:" + SaleAmt + "</b> <br/>Sale Date:" + SaleDate+ "<br/>Case Number:"+ CaseNumber+ "<br/>Address:"+ Addre\
ss+ "<br/>Zipcode:"+ ZipCode+ "<br/>Plaintiff:"+ Plaintiff+ "<br/>Defendant:"+ Defendant+ "<br/>Attorney:"+ Attorney+ "<br/>Sold to:"+ SoldTo+ "<br/>Parcel ID:"+ PID+ "<br/>Appraisal:"+ Appraisal+\
"<br/>Minimum bid:"+ MinBid+ "<br/>Sale amount:"+ SaleAmt+ "<br/> Sale status:"+ SaleStatus;
var icon = customIcons[SaleStatus] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, info);
markersArr.push(marker);
}
});
}
var customIcons = {
ACTIVE: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
CANCELLED: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_black.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
NOBIDNOSALE: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
SOLD: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markersArr[i].setMap(null);
}
markersArr.length = 0;
}
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(39.7620028,-84.3542049),
zoom: 10,
mapTypeId: 'roadmap'
});
infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
// downloadUrl("phpsqlajax_genxml3.php", function(data) {
downloadUrl( "phpsqlajax_genxml3dynamic.php?maxbid=54,000&minbid=0&salestatus=*&saledate=*", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var SaleDate = markers[i].getAttribute("SaleDate");
var CaseNumber = markers[i].getAttribute("CaseNumber");
var Address = markers[i].getAttribute("Address");
var ZipCode = markers[i].getAttribute("ZipCode");
var Plaintiff = markers[i].getAttribute("Plaintiff");
var Defendant = markers[i].getAttribute("Defendant");
var Attorney = markers[i].getAttribute("Attorney");
var SoldTo = markers[i].getAttribute("SoldTo");
var PID = markers[i].getAttribute("PID");
var Appraisal = markers[i].getAttribute("Appraisal");
var MinBid = markers[i].getAttribute("MinBid");
var SaleAmt = markers[i].getAttribute("SaleAmt");
var SaleStatus = markers[i].getAttribute("SaleStatus");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("Latitude")),
parseFloat(markers[i].getAttribute("Longitude")));
var info = "<b>Sale Date:" + SaleDate +"<br/>Address:"+ Address+"<br/>Sale Amount:" + SaleAmt + "</b> <br/>Sale Date:" + SaleDate+ "<br/>Case Number:"+ CaseNumber+ "<br/>Address:"+ Addre\
ss+ "<br/>Zipcode:"+ ZipCode+ "<br/>Plaintiff:"+ Plaintiff+ "<br/>Defendant:"+ Defendant+ "<br/>Attorney:"+ Attorney+ "<br/>Sold to:"+ SoldTo+ "<br/>Parcel ID:"+ PID+ "<br/>Appraisal:"+ Appraisal+\
"<br/>Minimum bid:"+ MinBid+ "<br/>Sale amount:"+ SaleAmt+ "<br/> Sale status:"+ SaleStatus;
var icon = customIcons[SaleStatus] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, info);
markersArr.push(marker);
}
});
}
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);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<form name='myForm'>
Min Bid $ :<input type='text' id='minbid' value='1,000' /> and
$ :<input type='text' id='maxbid' value='1,000,000' /> <br>
Sale Status:<select id='salestatus'>
<option value="*" selected>All</option>
<option>Active</option>
<option>Sold</option>
<option>Cancelled</option>
<option>No Bid, No Sale</option>
</select>
<br>
Sale Date:<select id='saledate'>
<option value="*" selected>All</option>
<option>2012-06-08</option>
<option>2012-06-01</option>
<option>2012-05-25</option>
<option>2012-05-18</option>
<option>2012-05-11</option>
<option>2012-05-04</option>
<option>2012-04-27</option>
<option>2012-04-20</option>
<option>2012-04-13</option>
<option>2012-04-06</option>
<option>2012-03-30</option>
<option>2012-03-23</option>
<option>2012-03-16</option>
<option>2012-03-09</option>
<option>2012-03-02</option>
</select>
<input type='button' onclick='updateMap()' value='Update Map' />
</form>
<div id="map" style="width: 95%; height: 85%"></div>
</body>
</html>
Again I'm 99.9% sure the php is fine since it returns valid results which are used to populate the field. I'm befuddled as to what I've done wrong for the update.
Hey SO this isn't spam let me post this dang question.
Your clearLocations function is looping over markers not markersArr which contains the existing marker references.
Should be
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markersArr.length; i++) {
markersArr[i].setMap(null);
}
markersArr.length = 0;
}