Inserting varianble GPS coordinates in google maps - php

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>

Related

Fetch Lat Long from table and mark on google map

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

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>

How to add marker on google map using jquery-ui-map

I am using http://code.google.com/p/jquery-ui-map/
HTML:
<div id="map_canvas" style="width: 100%; height:400px;" latitude="123456" longitude="123456">Loading Map</div>
jQuery:
$(function() {
$('#map_canvas').gmap({
'center': new google.maps.LatLng($('#map_canvas').attr('latitude'),$('#map_canvas').attr('longitude')),
'zoom': 13
});
});
It is working fine but I am unable to add a marker. I have tried many option in documentation but unable to place marker.
Any Idea?
Thanks
http://jquery-ui-map.googlecode.com/svn/trunk/demos/jquery-google-maps-basic-example.html
$('#map_canvas').gmap().bind('init', function(ev, map) {
$('#map_canvas').gmap('addMarker', {'position': '57.7973333,12.0502107', 'bounds': true}).click(function() {
$('#map_canvas').gmap('openInfoWindow', {'content': 'Hello World!'}, this);
});
});
and this is what I found:
http://code.google.com/apis/maps/documentation/javascript/overlays.html#MarkerAnimations
// Google Maps
function GoogleMaps() {
var latitude = $("#map_canvas").attr('latitude');
var longitude = $("#map_canvas").attr('longitude');
var location = new google.maps.LatLng(latitude, longitude);
var marker;
var map;
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: location
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
marker = new google.maps.Marker({
map:map,
animation: google.maps.Animation.DROP,
position: location
});
}
Working now

how to convert any address in latitude and longitude from google map in php?

I have used below code for displaying multiple marker in the google map and it works perfectly.
var locations = [
[51.481383, -3.114967, 'UK', 'Cardiff'],
[52.362393, 4.893379, 'NL', 'Amsterdam'],
[48.852314, 2.350089, 'FR', 'Paris'],
[40.18884, -3.716812, 'SP', 'Madrid'],
[53.800651, -4.064941, 'IT', 'Rome'],
[42.041134, 1.889648, 'SP', 'Costa Brava'],
[37.014581, -7.933888, 'PT', 'Algarve'],
[28.358776, -14.05426, 'PT', 'Fuerteventura'],
[29.046854, -13.589973, 'SP', 'Lanzarote']
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: new google.maps.LatLng(40.92, 1.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
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][0], locations[i][1]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][3]);
infowindow.open(map, marker);
}
})(marker, i));
}
Now my question is that,
In this code the location is added manually.
But i have the functionality to add the search box and and search by location(Address).
That means i have to convert the address location in to lat-long value.
So any one can extend this code?
use The Google Geocoding API
see this exmaple
code
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
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);
}
});
}
<body onload="initialize()">
<div id="map_canvas" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Encode" onclick="codeAddress()">
</div>
</body>

Categories