Add more results in google map dynamically - php

I am working on this from several hours but no success.
This code is working fine one time and add 100 records on map. Then I want to add more results from db after first 100. how can I do that please guide me. Here is the code.
I also try with ajax but json damage after result came back from php so that is also not work for me.
<div class="span12 geoData">
<?php
$db = new db();
$data = array();
$tweets = array();
$counter = 0;
$query = "SELECT * FROM `tweets` WHERE `geo_lat` != 0 LIMIT 100";
$results = $db->select($query);
$count = mysqli_num_rows($results);
while (($row = mysqli_fetch_assoc($results)) !=FALSE) {
$tweets[$counter]['tweet_text'] = $row['tweet_text'];
$tweets[$counter]['geo_lat'] = $row['geo_lat'];
$tweets[$counter]['geo_long'] = $row['geo_long'];
$counter++;
}
$data['count'] = $count;
$data['tweets'] = $tweets;
$jsonData = json_encode($data);
?>
<script src="mapsApi.js"></script>
<script src="markerclusterer_compiled.js"></script>
<script type="text/javascript">
var data = <?php echo $jsonData; ?>;
function initialize() {
var center = new google.maps.LatLng(39.744408452010475, -100.15602825000002);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infowindow = new google.maps.InfoWindow({
content: "holding..."
});
var markers = [];
for (var i = 0; i < data.count; i++) {
var contentSTR = '<div id="info"><p><span>Ttitle:</span> '+ data.tweets[i].tweet_text + '</p></div>';
var dataTweets = data.tweets[i];
var latLng = new google.maps.LatLng(dataTweets.geo_lat,
dataTweets.geo_long);
var marker = new google.maps.Marker({
position: latLng,
html: contentSTR,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-container">
<div id="map"></div>
</div>
</div>

Related

Google Map API Not displaying Markers JavaScript

I'm trying to grab latlng co-ords from my database to display them on a webpage which will dynamically update when a user searches for something specific but they aren't showing up at all.
<?php
include_once '../db/dbconnect.php';
$query = "SELECT * FROM property WHERE city='Sheffield' AND type='House'";
$result = $mysqli->query($sql);
$num_rows = mysql_num_rows($result);
if($num_rows > 0){
for($i=0;$i<$num_rows;$i++){
$row=mysql_fetch_row($result);
$location[] = $row[3].','.$row[6].','.$row[7].','.($i+1);
}
}
?>
I'm having problems with fetching the data from the database as $location doesn't seem to have any values inside of it.
I can see issue in your HTML code structure, you have started div tag but it ended after your javascript code. so please start div and end that div then write youyr javascript code as mentioned below.
<div id='map'></div>
<script type="text/javascript">
var locations = <?php echo json_encode($location); ?>;
var map;
function initMap() {
if(typeof locations !== "undefined")
{
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 53.3811, lng: -1.4701},
zoom: 13
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
alert(locations.length);
for (i = 0; i < locations.length; i++) {
loc_array = locations[i].split(",");
marker = new google.maps.Marker({
position: new google.maps.LatLng(loc_array[1], loc_array[2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(loc_array[0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCtf7Q1QeO9cQfwsBo7FQ-g3en_zJbk8Iw&callback=initMap" async defer></script>
I am not sure about this will work.
You php code should be
<?php
include_once '../db/dbconnect.php';
$query = "SELECT * FROM property WHERE city='Sheffield' AND type='House'";
$result = mysql_query($sql);
$location=array();
if(mysql_num_rows($result)> 0){
while($row=mysql_fetch_assoc($result)){
$location[] = array($row['lat'],$row['lng']);
}}
?>

Too much recurssion in google map

<script type='text/javascript'>
jQuery(document).ready(function($){
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds();
var encodedString;
var stringArray = [];
encodedString = document.getElementById("encodedString").value;
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
addressDetails = stringArray[x].split("&&&");
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
marker = new google.maps.Marker({
map: map,
position: lat,
//Content is what will show up in the info window
content: addressDetails[0]
});
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
</script>
</head>
<body>
<div id='input'>
<?php
$encodedString = "";
$x = 0;
$result = mysql_query("SELECT * FROM `table-name`");
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
if ( $x == 0 )
{
$separator = "";
}
else
{
$separator = "****";
}
$encodedString = $encodedString.$separator.
"<p class='content'><b>Lat:</b> ".$row[1].
"<br><b>Long:</b> ".$row[2].
"<br><b>Name: </b>".$row[3].
"<br><b>Address: </b>".$row[4].
"</p>&&&".$row[1]."&&&".$row[2];
$x = $x + 1;
}
?>
<input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
</div>
<div id="map_canvas"></div>
I have used above code for google map location from MySQL database.
Above code fetch lat, Lang from MySQL database and dynamically create google map.
When I run above code It gave me error like that:
There are two errors named too much recursion & initMap is not function.
Can anybody help me to sort out it.
Thanks in advance.
You have not defined initMap in your js file. That's why you are getting that error. You probably need to remove the callback part from the google map api script
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
To
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" async defer></script>
Also check if the lat and lon contain valid numeric values in the following statement
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);

Google maps code markers codes works on firefox but not chrome or safari

I am creating a user map system that allows users to either select a new location or select a saved location (from an sql file). I want the map to load with a draggable marker that can be used to select a new position, with the lat/lng populating the relevant fields on the form. I also want the saved locations to populate a dropdown menu, allowing the users to select a location, the lat/lng and name will then populate the relevant fields and the draggable marker disappears from the map. When ‘Select a new location’ is selected from the dropdown menu, the ‘saved locations’ markers disappear and the draggable marker should reappear.
This is the code I have. I admit I am new to this, and have used the Google Maps Developer a lot, as well as searching online and have taken quite a while to get to this point.
This code does exactly what I want in Firefox and IE, but not in Chrome or Safari. In Chrome the saved locations appear in the dropdown menu but when I click on ‘select a new location’ after I have loaded a saved location, the draggable marker does not reappear. In Safari, the saved locations are not even loaded. I would appreciate any advice on how I can fix the errors with my code that could be causing this. I have tried debugging in Chrome (31.0.1650.57 ) and Safari (5.1.7 for windows), I get Cannot read property '_e3' of undefined of the main.js and also Unexpected token <
error404.000webhost.com/ (I’m hosting the site on 000webhost).
This is my html code:
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Sightings Form Member</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var markers = [];
var markerNew;
var infoWindow;
var infowindow;
var locationSelect;
var geocoder = new google.maps.Geocoder();
var imageNew = 'binoculars3.png';
var imageSave = 'star-3a.png';
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
console.log(responses);
updateMarkerAddress(responses[0].address_components[0].long_name);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerPosition(latLng) {
var MapLat =latLng.lat();
var MapLng =latLng.lng();
document.getElementById('latitude').value = MapLat;
document.getElementById('longitude').value = MapLng;
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
infowindow.open(map, markerNew);
infowindow.setContent(address);
}
function initialize() {
var latLng = new google.maps.LatLng(10.6667, -61.3152);
map = new google.maps.Map(document.getElementById("map"), {
center: latLng,
zoom: 8,
mapTypeId: 'hybrid',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_left
}
});
infoWindow = new google.maps.InfoWindow();
NewMarker(latLng);
infowindow = new google.maps.InfoWindow();
infowindow.setContent(address);
// Adds saved locations //Set up dropdown options
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
//Read in saved locations
downloadUrl('RetrieveSavedLoc.php', function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("markerSave");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("loc_name");
var address = markerNodes[i].getAttribute("dayyear");
var savedlatlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
var MapLat = markerNodes[i].getAttribute("lat");
var MapLon = markerNodes[i].getAttribute("lng");
createOption(name, i);
createMarker(savedlatlng, name,MapLat,MapLon);
bounds.extend(savedlatlng);
}
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
///Set up new marker
function NewMarker(latLng,address) {
markerNew = new google.maps.Marker({
position: latLng,
icon: imageNew,
map: map,
draggable: true,
crossOnDrag:false
});
google.maps.event.addListener(markerNew, 'drag', function() {
updateMarkerPosition(markerNew.getPosition());
document.getElementById('locname').value = '';
});
google.maps.event.addListener(markerNew, 'dragend', function() {
geocodePosition(markerNew.getPosition());
var newlatLng = markerNew.getPosition(); // returns LatLng object
map.setCenter(newlatLng);
});
}
//Saved location marker
function createMarker(savedlatlng, name,MapLat,MapLon) {
var html = "<b>" + name + "</b>";
var marker = new google.maps.Marker({
map: map,
icon: imageSave,
position: savedlatlng,
visible: false
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.close(); //Close MarkerNew infowindow
markerNew.setVisible(false);//Close MarkerNew
marker.setVisible(true);
setAllMap(map); //Allows saved markers to be put back on map
infoWindow.setContent(html);
infoWindow.open(map, marker);
document.getElementById('latitude').value = MapLat;
document.getElementById('longitude').value = MapLon;
document.getElementById('locname').value = name;
});
markers.push(marker);
}
//Reads saved locations into dropdown menu
function createOption(name, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name;
locationSelect.appendChild(option);
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
markerNew.setVisible(true);
}
// Sets the map on all markers in the array.
function setNewMap(map) {
for (var i = 0; i < markerNew.length; i++) {
markerNew[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkerNew() {
google.maps.event.addListener(map, "click", function () {
markerNew.setMap(null);
alert("Marker has been removed from map, about to restore it");
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<body id = "main_body">
</div>
<div id="mainouter">
<div class = "form description">
<form action="reviewMember.php" method="post">
<label style="font-size:1.4em;font-color:black;" class="description" for="location" >Where did you see it?* </label>
<label class="description" for="location"></label>
<div><select id="locationSelect" name="locationSelect" style="width:400px">
<option value="loc_new" onclick="clearMarkers();">Select a new location</option>
</select></div>
<div id="map" style="height: 300px;width: 400px;margin-right: 0.9em;float:left;"></div>
</form>
</div>
</body>
</html>
And php:
<?php
require("connectMap.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$con=mysqli_connect ($server, $user, $pass,$db);
if (!$con) { die('Not connected : ' . mysqli_error($con));}
session_start();
if(!isSet($_SESSION["email"],$_SESSION['uid'])) {
// Redirect user to login page
header("Location: login_final.php");
exit();
}else {
$userEmail = $_SESSION["email"];
}
// Select the member ID from the users table - to search for the id in the database
$sql = "SELECT * FROM users WHERE email ='$userEmail' LIMIT 1";
$user_query = mysqli_query($con, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
exit();
}
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$userID = $row["ID"];
}
// Select the member from the database table - this is to find the name of the user to input into the form and save into form database
$query = "SELECT * FROM locations WHERE userID ='$userID' ";
$result = mysqli_query($con,$query);
$dayyear = "";
if (!$result) {
die('Invalid query: ' . mysqli_error($con));
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysqli_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("markerSave");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("loc_name",$row['locname']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
}
echo $dom->saveXML();
?>

Display multiple locations on Google Map v3 using PHP MYSQL WHILE LOOP

I have this code that was once working but now is not. It is for displaying multiple locations on a map using Google maps version 3, by getting the locations from a table in the database, and looping through them using a PHP WHILE loop. Only one location is being displayed. The code is as below:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map ;
function initialize() {
var latlng = new google.maps.LatLng(53.933056, 9.503611);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?
$query = mysql_query("SELECT
markers.id,
markers.place,
markers.address,
markers.lat,
markers.lng,
markers.description,
markers.type,
images.id,
images.thumb_path,
images.main
FROM
markers,images
WHERE
markers.type = '".$type."'
AND markers.id = images.id
AND images.main = 1
");
$numRows = mysql_num_rows($query);
if($numRows > 0){
while($row = mysql_fetch_assoc($query)){
?>
var contentString = '<div id="content">'+
'<img src="<?=$row['thumb_path'];?>" width="100" height="100" hspace="2" align="left" />'+
'<h4><?=$row['place'];?></h4><p><?=$row['address'];?></p>'+
'<p align="right">More Details'+
'</div>';
var marker = add_marker(<?=$row['lat'];?>, <?=$row['lng'];?>,"<?=strtoupper($row['place']);?>",contentString);
marker.setMap(map);
<? } ?>
<? } ?>
}
function add_marker(lat,lng,title,box_html) {
var infowindow = new google.maps.InfoWindow({
content: box_html
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
title: title
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
return marker;
}
Kindly assist.

passing variables into google maps and refresh

WORK FINE YET
I need to show only the items entered username and password.
I can not send php variables to javascript to call back to the database and update the map
I have this code work fine ( only part):
function initialize() {
var myOptions = {
zoom: 10,
//center: new google.maps.LatLng(-33.9, 151.2),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
<?
$query = mysql_query("SELECT lat2,lon2,idruta,FROM_UNIXTIME(time) as time FROM bus");
$valores="[";
$indice = 0;
while ($row = mysql_fetch_array($query)){
$namex=$row['idruta'];
$lat=$row['lat2'];
$lon=$row['lon2'];
$desc = $row['time'];
$name = $namex ." ".$desc;
$indice++;
$valores = $valores. "['$name',$lat,$lon,$indice],";
}
$valores = substr($valores, 0, -1);
$valores = $valores ."]";
echo ("setMarkers(map, $valores)");
?>
// setMarkers(map, beaches);
}
function codeAddress() {
var myOptions = {
zoom: 10,
//center: new google.maps.LatLng(-33.9, 151.2),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
<?
$query = mysql_query("SELECT lat2,lon2,idruta,FROM_UNIXTIME(time) as time FROM bus where user = $user");
$valores="[";
$indice = 0;
while ($row = mysql_fetch_array($query)){
$namex=$row['idruta'];
$lat=$row['lat2'];
$lon=$row['lon2'];
$desc = $row['time'];
$name = $namex ." ".$desc;
$indice++;
$valores = $valores. "['$name',$lat,$lon,$indice],";
}
$valores = substr($valores, 0, -1);
$valores = $valores ."]";
echo ("setMarkers(map, $valores)");
?>
}
function setMarkers(map, locations) {
var image = new google.maps.MarkerImage('marker-panel.png',
new google.maps.Size(220, 39),
new google.maps.Point(0,0),
new google.maps.Point(50, 39));
/* var shadow = new google.maps.MarkerImage('marker-panel.png',
new google.maps.Size(37, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));*/
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
//shadow: shadow,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
bounds.extend(myLatLng);
var label = new Label({
map: map
});
label.set('zIndex', 1234);
label.bindTo('position', marker, 'position');
label.set('text', beach[0]);
//label.bindTo('text', marker, 'position');
}
map.fitBounds(bounds);
}
</script>
</head>
<body onload="initialize()">
<div>
<input id="usuario" type="textbox" value="usuario">
<input id="password" type="password" value="password">
<input type="button" value="Enviar" onclick="codeAddress()">
</div>
<div id="map_canvas" style="height:90%;top:30px"></div>
</body>
</html>
but I need to show only the user points and password entered. And i don´t know
thanks
Before calling those java script function write one php code to check userpoints and password.If userpoints and password is correct means only those scripts are called.

Categories