Google Maps multiple markers position ZOOM ERROR - php

I just registered to ask for help with google maps. I'm working on a project that allows me to insert various ads of homes in the google map on my site. I do not know why that position is never correct, at first I tried using the code below ...
Then I had to delete the variables city, street, state, and zipcode why they went to war. But without resolving anything. So go to the link to better understand the situation. The generated code is in the script tag to the top of the map div.
LINK
<script>var defaultmapcenter = {mapcenter: "<?php echo $ct_options['ct_home_map_center']; ?>"}; google.maps.event.addDomListener(window, 'load', function(){ estateMapping.init_property_map(property_list, defaultmapcenter); });</script>
<script>
var property_list = [];
var default_mapcenter = [];
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); $count++; ?>
var property = {
thumb: "<?php ct_first_image_tn_map() ?>",
price: "<?php currency(); ?><?php map_pin_price(); ?>",
fullPrice: "<?php currency(); ?><?php listing_price(); ?>",
bed: "<?php beds(); ?>",
bath: "<?php baths(); ?>",
size: "<?php echo get_post_meta($post->ID, "_ct_sqft", true); ?> <?php sqftsqm(); ?>",
street: "<?php the_title(); ?>",
city: "<?php city(); ?>",
state: "<?php state(); ?>",
zip: "<?php zipcode(); ?>",
latlong: "<?php echo get_post_meta(get_the_ID(), "_ct_latlng", true); ?>",
permalink: "<?php the_permalink(); ?>",
agentThumb: "<?php echo get_template_directory_uri(); ?>/img_resize/timthumb.php?src=<?php the_author_meta('ct_profile_url'); ?>&w=40&zc=1'",
agentName: "<?php the_author_meta('first_name'); ?> <?php the_author_meta('last_name'); ?>",
agentTagline: "<?php if(get_the_author_meta('tagline')) { the_author_meta('tagline'); } ?>",
agentPhone: "<?php if(get_the_author_meta('office')) { the_author_meta('office'); } ?>",
agentEmail: "<?php if(get_the_author_meta('email')) { the_author_meta('email'); } ?>",
isHome: "<?php if(is_home()) { echo "false"; } else { echo "true"; } ?>",
commercial: "<?php if(has_type('commercial')) { echo 'commercial'; } ?>"
}
property_list.push(property);
<?php
endwhile; endif;
wp_reset_query();
?>
</script>
<script>var defaultmapcenter = {mapcenter: "<?php echo $ct_options['ct_map_center']; ?>"}; google.maps.event.addDomListener(window, 'load', function(){ estateMapping.init_property_map(property_list, defaultmapcenter); });</script>
**Javascript:**
---------------
var estateMapping = (function () {
var self = {},
marker_list = [],
open_info_window = null,
x_center_offset = 0, // x,y offset in px when map gets built with marker bounds
y_center_offset = -100,
x_info_offset = 0, // x,y offset in px when map pans to marker -- to accomodate infoBubble
y_info_offset = -100;
function build_marker(latlng, property) {
var marker = new MarkerWithLabel({
map: self.map,
draggable: false,
flat: true,
labelContent: property.price,
labelAnchor: new google.maps.Point(22, 0),
labelClass: "label", // the CSS class for the label
labelStyle: {opacity: 1},
icon: 'wp-content/themes/reale/images/blank.png',
position: latlng
});
self.bounds.extend(latlng);
self.map.fitBounds(self.bounds);
self.map.setCenter(convert_offset(self.bounds.getCenter(), x_center_offset, y_center_offset));
var infoBubble = new InfoBubble({
maxWidth: 275,
content: contentString,
borderRadius: 4,
disableAutoPan: true
});
var residentialString = '';
if(property['commercial'] != 'commercial') {
var residentialString='<p class="details">'+property.bed+' '+property.bath+'';
}
var contentString =
'<div class="info-content">'+
'<img class="left" src="'+property.thumb+'" />'+
'<div class="listing-details left">'+
'<h3>'+property.street+'</h3>'+
'<p class="location">'+property.city+', '+property.state+' '+property.zip+'</p>'+
'<p class="price"><strong>'+property.fullPrice+'</strong></p>'+residentialString+', '+property.size+'</p></div>'+
'</div>';
var tabContent =
'<div class="info-content">'+
'<img class="left" src="'+property.agentThumb+'" />'+
'<div class="listing-details left">'+
'<h3>'+property.agentName+'</h3>'+
'<p class="tagline">'+property.agentTagline+'</p>'+
'<p class="phone"><strong>Tel:</strong> '+property.agentPhone+'</p>'+
'<p class="email">'+property.agentEmail+'</p>'+
'</div>'+
'</div>';
infoBubble.addTab('Details', contentString);
infoBubble.addTab('Contact Agent', tabContent);
google.maps.event.addListener(marker, 'click', function() {
if(open_info_window) open_info_window.close();
if (!infoBubble.isOpen()) {
infoBubble.open(self.map, marker);
self.map.panTo(convert_offset(this.position, x_info_offset, y_info_offset));
open_info_window = infoBubble;
}
});
}
function geocode_and_place_marker(property) {
var geocoder = new google.maps.Geocoder();
var address = property.street+', '+property.city+' '+property.state+', '+property.zip;
//If latlong exists build the marker, otherwise geocode then build the marker
if (property['latlong']) {
var lat = parseFloat(property['latlong'].split(',')[0]),
lng = parseFloat(property['latlong'].split(',')[1]);
var latlng = new google.maps.LatLng(lat,lng);
build_marker(latlng, property);
} else {
geocoder.geocode({ address : address }, function( results, status ) {
if(status == google.maps.GeocoderStatus.OK) {
var latlng = results[0].geometry.location;
build_marker(latlng, property);
}
});
}
}
function init_canvas_projection() {
function CanvasProjectionOverlay() {}
CanvasProjectionOverlay.prototype = new google.maps.OverlayView();
CanvasProjectionOverlay.prototype.constructor = CanvasProjectionOverlay;
CanvasProjectionOverlay.prototype.onAdd = function(){};
CanvasProjectionOverlay.prototype.draw = function(){};
CanvasProjectionOverlay.prototype.onRemove = function(){};
self.canvasProjectionOverlay = new CanvasProjectionOverlay();
self.canvasProjectionOverlay.setMap(self.map);
}
function convert_offset(latlng, x_offset, y_offset) {
var proj = self.canvasProjectionOverlay.getProjection();
var point = proj.fromLatLngToContainerPixel(latlng);
point.x = point.x + x_offset;
point.y = point.y + y_offset;
return proj.fromContainerPixelToLatLng(point);
}
self.init_property_map = function (properties, defaultmapcenter) {
var options = {
zoom: 1,
center: new google.maps.LatLng(defaultmapcenter.mapcenter),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
streetViewControl: false
};
self.map = new google.maps.Map( document.getElementById( 'map' ), options );
self.bounds = new google.maps.LatLngBounds();
init_canvas_projection();
//wait for idle to give time to grab the projection (for calculating offset)
var idle_listener = google.maps.event.addListener(self.map, 'idle', function() {
for (i=0;i<properties.length;i++) {
geocode_and_place_marker(properties[i]);
}
google.maps.event.removeListener(idle_listener);
});
}
return self;
}());

I took a couple of property objects from your live site and simplified the code. This seems to position the markers correctly. There's too much code in your question to tell exactly where you went wrong, but if you start with this demo, you can add your functionality back slowly and see where it breaks.
Demo:
Output:
Script:
var property_list = [
{latlong: "36.738884,15.022705"},
{latlong: "42.608127,14.067408"}
],
options = {
zoom: 4,
center: new google.maps.LatLng( 36.73, 15.02 ),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(
document.getElementById( 'map-canvas' ),
options
);
for( var index = 0; index < property_list.length; index++ ) {
var latlong = property_list[index]['latlong'].split(','),
latlng = new google.maps.LatLng( latlong[0], latlong[1] ),
marker = new google.maps.Marker( {position: latlng, map: map} );
marker.setMap( map );
};
HTML:
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>
CSS:
#map-canvas {
height: 300px;
width: 500px;
}

There is nothing wrong with your markers and the javascript-code, all(except one) of the markers are placed at the correct position.
The issue is your content. You may have noticed that the shadow of the 265k-marker is much darker than the 1k-marker. It's because behind that marker are 8 other markers, 9 of your markers are defined with an equal LatLng.
Only 1 marker is not shown, it's the marker with an empty latlong. The geocoding fails here because of the missing properties street,city,state and zip.

replace this line
var address = property.street+', '+property.city+' '+property.state+', '+property.zip+', '+property.country;
with these lines to remove the fields with empty values
var city = (property.city.trim() != '')?property.city.trim()+',':'';
var state = (property.state.trim() != '')?property.state.trim()+',':'';
var country = (property.country.trim() != '')?property.country.trim():'';
var address = city+state+country;

Related

google map v3 OVER_QUERY_LIMIT - Geocoding with PHP MYSQL

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.

Google Map not loading when running script (shows "map div")

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>

Trying to make an array of latitude and longitudes dynamically in php

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.

Retrieving JSON formated results using php post request in ajax via jquery, to be used in adding google map Marker closed

Just doing a small project relating to google maps.
Basically I have coordinates in a database that I want to retrieve using ajax, and update the map without the need to refresh the page.
php part:-
$deviceID = $_POST['deviceID'];
$sqlLocation = "SELECT * FROM Location WHERE DeviceID = '".$deviceID."' AND Type ='network'";
$sqlResult = mysql_query($sqlLocation);
while($row = mysql_fetch_assoc($sqlResult))
{
$response["uid"] = $row["DeviceID"];
$response["deviceInfo"]["Longitude"] = $row["Longitude"];
$response["deviceInfo"]["Latitude"] = $row["Latitude"];
$response["deviceInfo"]["Type"] = $row["Type"];
$response["deviceInfo"]["latlontime"] = $row["latlontime"];
echo json_encode($response);
}
the format of the multiple json result :-
{"uid":"*deviceID here*","deviceInfo":
{"Longitude":"x.xxxxxxx","Latitude":"x.xxxxxxx","Type":"network","latlontime":"2012-05-05 18:55:12"}
}
{"uid":"*deviceID here*","deviceInfo":
{"Longitude":"y.yyyyyyyyy","Latitude":"y.yyyyyyyyy","Type":"network","latlontime":"2012-05-05 18:55:56"}
}
javaScript part with some pseudo code sorry !
var map;
var count =0;
function initialize(DeviceID)
{
if(DeviceID!=null)
{
$.ajax({
type:"POST",
dataType:"json",
data:{deviceID: DeviceID},
url: "json_coords.php",
contentType: "application/json; charset=utf-8",
success: function(data)
{
*****problem used be here******
var len = data.length;
for( var i = 0; i<len; i++)
{
var json_row = data[i];
var latitude = json_row.deviceInfo.Latitude;
var longitude = json_row.deviceInfo.Longitude;
var title = "pos: "+i+json_row.deviceInfo.Type + " "
+json_row.deviceInfo.latlontime ;
//alert_test(latitude,student.Longitude);
setMarker(latitude,longitude,title);
*********************************************************************************
}
}
});
}
else
{
// do nothing
}
var latloncenter = new google.maps.LatLng(51,-1.4469157);
var myOptions =
{
zoom: 4,
center: latloncenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function setMarker(lat,lon,titletxt)
{
var latlongMarker = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker
(
{
position: latlongMarker,
map: map,
title:titletxt
}
);
}
the initialize function will be called after pressing a certain divs on the website:-
$('#leftcolumn>a').click(function()
{
var deviceID = $(this).attr("name");
//alert(deviceID);
initialize(deviceID)
});
I would really appreciated if you can help me out
Thank you :)
* the original problem was around how to retrieve data from a php page with json results**
the Ajax function of jQuery (in JSON mode) expected a unique json object, you ara sending 2, the format is invalid.
You can do:
$response = array();
while($row = mysql_fetch_assoc($sqlResult))
{
$response[] = (object) array(
'uid' => $row["DeviceID"],
'deviceInfo' => (object) array (
'Longitude' => $row["Longitude"],
'Latitude' => $row["Latitude"],
'Type' => $row["Type"],
'latlontime' => $row["latlontime"]
)
);
}
echo json_encode($response);
And onsuccess callback:
success: function(data) {
$.each(data, function (device) {
var title = device.Type + ' ' + device.latlontime;
setmarker( device.Longitude ,device.Latitude , title);
});
}
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&region=GB"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body onload="initialize();">
<div id="map_canvas" style="height:300px;width:500px"></div>
Load markers
<script type="text/javascript">
var map;
var count =0;
function initialize()
{
var latloncenter = new google.maps.LatLng(51,-1.4469157);
var myOptions =
{
zoom: 4,
center: latloncenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function loaddata(DeviceID)
{
if(DeviceID!=null)
{
$.ajax({
type: "POST",
dataType: "json",
data:{deviceID: DeviceID },
url: 'mapdata.php',
success: function(data)
{
$.each(data,function(index,value) {
console.log(value);
/// I know there is no such thing as data.jsonGetvalueByID just trying to explain what I want to do
var longitude = value.deviceInfo.Longitude;
var latitude = value.deviceInfo.Latitude;
var type = value.deviceInfo.Type;
var time = value.deviceInfo.latlontime;
var title = type + " " +time;
//calling function to add map marker
createmarker(longitude, latitude, title);
});
}
});
}
}
function createmarker(lat,lon,titletxt)
{
var latlongMarker = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker
(
{
position: latlongMarker,
map: map,
title:titletxt
}
);
return marker;
}
</script>
</body>
</html>
// my ajax file that just fakes the data needed, so replace with your database code.
<?php
$response = array();
$rows = array();
$rows[] = array("DeviceID"=>1,"Type"=>"Network","Longitude"=>"51.4343","Latitude"=>"-2.344","latlontime"=>date("Y-m-d H:i:s"));
$rows[] = array("DeviceID"=>2,"Type"=>"Network","Longitude"=>"55.4343","Latitude"=>"-2.644","latlontime"=>date("Y-m-d H:i:s"));
foreach ($rows as $row)
{
$data["uid"] = $row["DeviceID"];
$data["deviceInfo"]["Longitude"] = $row["Longitude"];
$data["deviceInfo"]["Latitude"] = $row["Latitude"];
$data["deviceInfo"]["Type"] = $row["Type"];
$data["deviceInfo"]["latlontime"] = $row["latlontime"];
$response[] = $data;
}
echo json_encode($response);
?>

Google Map marker window

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>";

Categories