I got latitude,longitude and address from the database. How to show each store values on google map:
$qry = mysqli_query($link,"select * from store");
while($row = mysqli_fetch_array($qry)){
$lat = $row['lat'];
$long = $row['lng'];
$adresse = $row['Adresse'];
}
How to show each store with the address one after another on google map.In my code, it only shows one map.how to show each map?
//JS function
window.onload=initMap;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
});
show_markers();
}
/*
Considering you have php array with locations
in format ('address'=>add1,'lat'=>lat1,'lng'=>lng1)
$qry = mysqli_query($link,"select * from store");
$marker_data = mysqli_fetch_array($qry);
*/
function show_markers(){
var locations = <?php echo json_encode($marker_data);?>;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]['lat'], locations[i]['lng']),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i]['address']);
infowindow.open(map, marker);
}
})(marker, i));
}
}
reffer map related code :https://developers.google.com/maps/documentation/javascript/adding-a-google-map
Related
I want to show all the data of markers that have the same latitude and longitude INTO SINGLE INFO WINDOW using PHP and MySQL. I have codes here but the info window of the markers that have the same spot is not showing.
Here is my php code
<?php
require_once "dbcon.php";
// Fetch the marker info from the database
$result = $conn->query("SELECT * FROM locations");
// Fetch the info-window data from the database
$result2 = $conn->query("SELECT * FROM locations WHERE (latitude, longitude) IN (
SELECT latitude, longitude FROM locations GROUP BY latitude, longitude HAVING count(*) > 1
)");
?>
here is the javascript
<script>
function initMap() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the web page
map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
map.setTilt(100);
// Multiple markers location, latitude, and longitude
var markers = [
<?php if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '["'.$row['name'].'", '.$row['latitude'].', '.$row['longitude'].',
"'.$row['icon'].'"],';
}
}
?>
];
// Info window content
var infoWindowContent = [
<?php if($result2->num_rows > 0){
while($row = $result2->fetch_assoc()){ ?>
['<div class="info_content">' +
'<h3><?php echo $row['name']; ?></h3>' +
'<p><?php echo $row['info']; ?></p>' + '</div>'],
<?php }
}
?>
];
// Add multiple markers to map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Place each marker on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
icon: markers[i][3],
title: markers[i][0]
});
// Add info window to marker
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Center the map to fit all markers on the screen
map.fitBounds(bounds);
}
// Set zoom level
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}
// Load initialize function
google.maps.event.addDomListener(window, 'load', initMap);
</script>
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']);
}}
?>
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>
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 would like to display over 100 locations each with detailed bubble contents (ie Company Name, Address, Phone Number, Website, Industry) on a custom Google Map. How can I fetch these locations from a MySQL database using Google Maps API 3 and PHP?
say you have an sql database of this type:
id/lat/lon/comment
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key= **your key** &sensor=true">
</script>
$sqlprep = "SELECT * FROM table_name";
$doselect = mysql_query($sqlprep);
echo "<script> var locations = [";
while ($loc = mysql_fetch_assoc($doselect)){
echo "['" .$loc[comment] ."', " . $loc['lat'] . ", " . $loc['lon'] . "";
}
echo " ];</script>";
and then in your java:
<script>jQuery(window).ready(function(){
function initialize() {
var myLatlng = new google.maps.LatLng( YOUR CENTER LAT,LAN HERE );
var myOptions = {
center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var infowindow = new google.maps.InfoWindow()
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
//adding the pop up windows here:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
initialize() ;
}); </script>
your html should be something like:
<html>
<body >
<div id="map_canvas" >
</div>
</body>
</html>
i might be missing some parentheses but you get the point ;)
hope it helps even 8 months later :)