Fetch Lat Long from table and mark on google map - php

I'm using php and I want to fetch two columns from table like Latitude and Longitutde and add the markers on google map based on lat and long values, how i do..

After you get latitude and longitude data,
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {lat: <?php echo $lat; ?>, lng: <?php echo $lng; ?>};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
API Key must be included

Related

Find Google map location by Get variable

I just wondered if anyone knew of a simple script available that will do the following:
Show Google map location of a particular vendor by getting its name from URL. Like we see in various listing websites like Justdial, IndiaMart, Zomato and a lot more. More clearly if my URL is
www.example.com/list.php?city=Delhi
It will show Delhi on google map embed on my list.php web page.
Does anyone know if something like this already exists in PHP?
Thanks in advance.
This will help you.
Html Part.
<div id="map" style="width:100%; height:500px;"></div>
Javascript:
function initMap() {
var latitude = your latitude;
var longitude = Your longitude;
var myLatlng = {lat: parseFloat(latitude), lng: parseFloat(longitude)};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: myLatlng
});
var address = Address;
var infowindow = new google.maps.InfoWindow({
content: address
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Click to zoom'
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
}
And finally you have to include map library.
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=Google key&callback=initMap">
</script>

Load markers from mysql database and display as markers on Google maps

I am using phonegap and I have a google map which locates the user and places a marker on the map. What I want to do is load markers from a mysql database which holds lat and long details for each place. Do I have to do this through php and ajax? This is the code I have at the moment. Thanks
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Test</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript">
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError,{'enableHighAccuracy':false,'timeout':10000});
}
//GEOLOCATION
var onSuccess = function(position) {
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
var myLatlng = new google.maps.LatLng(myLat, myLong);
//MAP
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body onload="onLoad()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Define map
var map;
Initialize map:
function initialize(lat,lng, n) { //BY PASSING LATITUDE (lat), LONGITUDE (lng) AND THE TEXT (n) WILL SET A DEFAULT MARKER
var mapOptions = {
scaleControl: true,
center: new google.maps.LatLng(lat, lng),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
});
var infowindow = new google.maps.InfoWindow();
infowindow.setContent('<b>ا'+n+'</b>');
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
call this function in device ready function.
You can pass current lat, long-
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
call a ajax request and get location data from server.
Insert all latitude and longitude in locations array within your ajax success request and call setMarkers method
var loc_array = new Array(); //LOCATION ARRAY
$.each(server_response_array, function(i,v){
loc_array[i] = [v.lat, v.lng, v.temp_txt];
}
setMarkers(loc_array);
function setMarkers(locations){
//clearMap();
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker, i
for (i = 0; i < locations.length; i++)
{
var loan = locations[i]['txt'];
var lat = locations[i]['lat'];
var lng = locations[i]['lng'];
latlngset = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
map: map, title: loan , position: latlngset, icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png' //THIS WILL SET A BLUE COLOR MARKER YOU CAN SET MORE COLOR AND ALSO CAN MANAGE FROM DATABASE
});
//map.setCenter(marker.getPosition())
var content = loan;
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
}
}
Also see this link
goole-map-javascript-api-unable-to-load-markers-from-mysql-database

How to show multiple areas by location in google maps using php

Here is the Initialise function.....
function initialize() {
Here the variables $Latitude,$Longitude are array values so how can i store them in Javascript Variables so that they can store the above array values....
var lat='<?php echo $Latitude?>';
var lon='<?php echo $Longitude?>';
var latlng = new google.maps.LatLng(lat,lon);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Here how can i loop the geocoder to show multiple areas using above array variables...
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!"
});
}
Its my sample code to plot multiple areas in google map by using area name or lat,lng.
var map;
var geocoder;
var marker;
var people = new Array();
var latlng;
var infowindow;
$(document).ready(function() {
ViewCustInGoogleMap();
});
function ViewCustInGoogleMap() {
var mapOptions = {
center: new google.maps.LatLng(11.0168445, 76.9558321), // Coimbatore = (11.0168445, 76.9558321)
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Get data from database. It should be like below format or you can alter it.
var data = '[{ "DisplayText": "adcv", "ADDRESS": "Jamiya Nagar Kovaipudur Coimbatore-641042", "LatitudeLongitude": "10.9435131,76.9383790", "MarkerId": "Customer" },{ "DisplayText": "abcd", "ADDRESS": "Coimbatore-641042", "LatitudeLongitude": "11.0168445,76.9558321", "MarkerId": "Customer"}]';
people = JSON.parse(data);
for (var i = 0; i < people.length; i++) {
setMarker(people[i]);
}
}
function setMarker(people) {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if ((people["LatitudeLongitude"] == null) || (people["LatitudeLongitude"] == 'null') || (people["LatitudeLongitude"] == '')) {
geocoder.geocode({ 'address': people["Address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
html: people["DisplayText"],
icon: "images/marker/" + people["MarkerId"] + ".png"
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
else {
alert(people["DisplayText"] + " -- " + people["Address"] + ". This address couldn't be found");
}
});
}
else {
var latlngStr = people["LatitudeLongitude"].split(",");
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false, // cant drag it
html: people["DisplayText"] // Content display on marker click
//icon: "images/marker.png" // Give ur own image
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
}
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA7IZt-36CgqSGDFK8pChUdQXFyKIhpMBY&sensor=true" type="text/javascript"></script>
<div id="map-canvas" style="width: 800px; height: 500px;">
</div>
This should work for you assuming lat and lon are javascript arrays with the same length:
var map = null;
function initialize() {
var lat='<?php echo $Latitude?>';
var lon='<?php echo $Longitude?>';
// initialize map center on first point
var latlng = new google.maps.LatLng(lat[0],lon[0]);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds();
for (var i=0, i<lat.length; i++) {
var latlng = new google.maps.LatLng(lat[i],lon[i]);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!"
});
}
// zoom and center the map to show all the markers
map.fitBounds(bounds);
}
<?php
/* lat/lng data will be added to this array */
try{$work=$_GET["service"];}catch(Exception $e){echo 'Authorization Failed.Map may Misbehave or Buggy.Click here to report this';}
$locations=array();
$uname="root";
$pass="";
$servername="localhost";
$dbname="bcremote";
$db=new mysqli($servername,$uname,$pass,$dbname);
$query = $db->query('SELECT * FROM location');
while( $row = $query->fetch_assoc() ){
$name = $row['uname'];
$longitude = $row['longitude'];
$latitude = $row['latitude'];
/* Each row is added as a new array */
$locations[]=array( 'name'=>$name, 'lat'=>$latitude, 'lng'=>$longitude );
}
//echo $locations[0]['name'].": In stock: ".$locations[0]['lat'].", sold: ".$locations[0]['lng'].".<br>";
//echo $locations[1]['name'].": In stock: ".$locations[1]['lat'].", sold: ".$locations[1]['lng'].".<br>";
?>
<script>
//var myLatLng = {lat: -25.363, lng: 131.044};
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: false,
zoom: 4
});
<?php for($i=0;$i<sizeof($locations);$i++)
{ ?>
var marker = new google.maps.Marker({
map: map,
position: {lat: <?php echo $locations[$i]['lat']?>,lng: <?php echo $locations[$i]['lng']?>},
title: 'Service'
});
<?php } ?>
}
</script>
This code Snippet uses Dynamic Content without using JSON or XML. This below code is what we see in the Browser View Source tool. Hope this helps you...
<script>
//var myLatLng = {lat: -25.363, lng: 131.044};
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: false,
zoom: 4
});
var marker = new google.maps.Marker({
map: map,
position: {lat: 192.652.231.25,lng: 192.652.231.25},
title: 'Service'
});
var marker = new google.maps.Marker({
map: map,
position: {lat: 192.652.231.25,lng: 192.652.231.25},
title: 'Service'
});
}
</script>
UPDATE 2017
Google maps now supports the creation of maps with multiple locations which you can embed via iframe! Source: https://www.create.net/support/218-how-to-pin-point-multiple-locations-on-google-maps.html
Go to https://www.google.com/maps
Make sure you're signed in - you can do so by clicking the Login button in the top-right corner.
In the top left corner, next to the search box, click the menu icon to expand the menu
Click "Your Places", "Maps" and then click "Create Map" to edit your map.
A new window will pop up. Give your map a title and description, then click "Save".
You can now pinpoint locations manually by clicking the marker icon and placing it directly onto the map, or search for locations using the search box at the top of the screen.
If you're adding locations manually, you can name the location and save to add it to the map. If you're searching and adding specific locations, a green marker will appear on the map and you can click the 'Add to map' link.
Repeat steps 6 and 7 for each location you wish to plot.
Once you have done that save your map again and refresh the page. Then, to get the code to embed your map on to your Create website, please follow these steps:
Make sure you map is public. You can do this by clicking 'Share' beneath the map name.
Under 'Who has access' click 'Change' and make turn it 'On - Public on the web' and save.
Next, click the menu icon and click on the link 'Embed on my site'
The code will then pop up in a new window.
To use this, you will need to paste the code into an HTML fragment on your Create account, and then place the HTML fragment on your chosen page.
Example:
<iframe src="https://www.google.com/maps/d/embed?mid=1tX88xmVMIFW9DQneDff_ZMJtekc" width="100%" height="480"></iframe>

Inserting varianble GPS coordinates in google maps

I want my script to get the latitude and longittude coordinates from a GPS(mobile phone) and then insert them into a google map and display the location of the Mobile phone. Well , i am able to retrieve the Lat,Long coordinates from the GPS but it won't insert them as the çentre'of the map displayed. My code :
<script>
$(document).ready(function(){
navigator.geolocation.getCurrentPosition(useposition);
});
function useposition(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
$("#location").html('Lat: ' + lat + '<br />Lon: ' + lon);
}
</script><meta name="viewport" content="initial-scale=1.0, user-scalable=no"<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script><script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(54,-1);
var settings = {
zoom: 15,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"), settings);
var marker = new google.maps.Marker({ position: latlng, map: map, title:"Yeah buddy!" })};
</script>
As You can see i Fetch the GPs coordinates and i want to insert them in my map which i load with :<body onload="initialize ()" > </body>
I just do not know how to make a variable from lat,lon and how to insert it properly in gogle maps . Help me please.
I assume by 'insert coordinates into the map' you mean add a marker at that location?
The first problem you'll have is your map variable is a local variable to your initialize function. So you could make that a global variable. Then in your useposition function you can simply create a new marker.
<script>
var map;
$(document).ready(function(){
navigator.geolocation.getCurrentPosition(useposition);
});
function useposition(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
$("#location").html('Lat: ' + lat + '<br />Lon: ' + lon);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lon),
map: map,
title:"Your Mobile" });
}
function initialize() {
var latlng = new google.maps.LatLng(54,-1);
var settings = {
zoom: 15,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), settings);
var marker = new google.maps.Marker({ position: latlng, map: map, title:"Yeah buddy!" })
};
</script>

Google Maps API v3 - Simple but add Geocode of address from php/mysql

I have this simple hello world version of a google map api javascript v3 and it works for a static geocode. My data is normal addresses (i.e. "30 rockefeller center, New York, NY").
This data is being called from with php from a mysql database. I can get the address on the page with something like this...For the purpose of this post, say this would have all info: address, city, state, zip code
<?php echo $row_query_details['address'];?>
So, I need to geocode this info for the map. I'm very comfortable with mysql and php, but not as much with javascript. I have been trial/error and researching this for a couple of days.
I have looked everywhere for a working sample or example and feel like this relatively simple problem must have been asked and answered many times over, but I cannot figure it out!
Thanks in advance.
Here is the code I'm working with:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: latlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:500px"></div>
</body>
</html>
Hello and happy anniversary (regarding your question and tutorial).
I am a web-developer and must thank you. I used this tutorial as I currently do not have a way to geocode via submit (lat/long needs to be pulled from address stored in db) as I am consulting an existing site and have minimal access to backend code.
To answer your question regarding marker interactivity, this takes a few easy steps:
1) Provide some content. This is done before declaring the geocoder (var geocoder;):
var contentString =
'line 1'+
'line 2';
2) Underneath the marker declaration ( var marker = new google.maps.Marker({ ), you will need to declare infowindow and add the event listener:
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
Edit:
I have successfully pulled array information from a MySQL database by expanding on your method. My method is here:
1) Basic php below:
include (dbinfo.php)
$result = mysql_query( 'SELECT * FROM table')
$count = 0
2) Setting up google maps API:
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=yourkey&sensor=false">
</script>
3) Geocoding setup below:
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
var latlng = new google.maps.LatLng(yourlat, yourlong); //This is to center the map
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php //Starts while loop so all addresses for the given information will be populated.
while($row = mysql_fetch_array($result)) //instantiates array
{ ?>
geocoder = new google.maps.Geocoder();
var address = '<?php echo $row['address'].', '.$row['city'].', '.$row['state'].', '.$row['zip'].', '.$row['country']; ?>';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//marker generation is done though adding the primary ID to the "marker" variable, so if address "1" has the primary ID of "1", your marker would read "marker1"
var marker<?php print $row['primaryID']; ?> = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "This can be a php variable or whatever you like. It is displayed on hover."
});
//var contentString manages what is seen inside of the popup
var contentString =
'line 1'+
'line 2';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker<?php print $row['primaryID']; ?>, 'click', function() {
infowindow.open(map,marker<?php print $row['primaryID']; ?>);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
<?php
$count++;
} //ends while
?>
}
/*end javascript*/
</script>
Thank you very much again for posting this. It was very useful.
You can use your PHP variable into JavaScript by passing php variables in function initialize().
your body tag will look like below;
For Ex:
<body onload="initialize('<?php echo $row_query_details['address'];?>')">
Then you will use this particular variable in your javascript code, your javascript function will look like below:
<script type="text/javascript">
function initialize(address) {
var G_address = address;
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: latlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
</script>
Now you can use this G_address JavaScript variable dynamically in your G-MAP code..
This will be helpful to you..
So, I'm going to answer my own question here. The first answer provided I was not able to utlize. I'm not sure if the answer was incomplete or I just didnt' follow it. Regardless, here's what the code looks like:
First I had my address components pulling from the mysql db and I assigned them variables, like this:
$county = $row_qry['county'];
$address = $row_qry['address'];
$city = $row_qry['city'];
$state = $row_qry['state'];
Then, my google v3 stuff looks like this:
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.052234,-118.243685);
var address = '<?php echo $address.', '.$city.', '.$state; ?>';
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode( { 'address': 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
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
And that sort of answers my question. There are a couple of issues I still need to resolve, such as (a) how to make the marker be clickable and interactive, and (b) the map flashes a the geocode first defined (34.05,-118.24) before showing the correct address.
Both of these issues I need to still resolve, but at least the geocoding is working successfully. Hope this helps someone else.
Thanks!

Categories