I am trying to include google maps on a homepage for the first time and just found the code which creates a google map with a particular location -
var myLatlng1 = new google.maps.LatLng(53.65914, 0.072050)
and I don't know how to change the location where the marker is- where can I find the location coordinates? Thanks!
<html>
<head>
<title> Map </title>
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 500px;
width: 800px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">
</script>
<script>
var map;
function initialize()
{
var myLatlng1 = new google.maps.LatLng(53.65914, 0.072050);
var mapOptions =
{
zoom: 10,
center: myLatlng1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
<?php
$sql = mysql_query("SELECT * FROM data ORDER BY ID DESC");
while($row =mysql_fetch_array($sql))
{
$desc = $row['DESCRIPTION'];
$location = $row['LOCATION'];
$counter += 1;
?>
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $location; ?>),
map: map,
title: '<?php echo $desc; ?>',
icon: '/image/cam.png'
});
navigator.geolocation.getCurrentPosition(showPosition);
}
var showPosition = function (position)
{
map.setCenter(new google.maps.LatLng(position.coords.latitude,
position.coords.longitude), 16);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
This is easy . First go to google maps and select the location you want to zoom in on. Once there look at the url at the top of the page it should look like this:
https://www.google.com/maps/#44.0005355,-71.0799974,12z
This is your lat long 44.0005355 and -71.0799974 Just replace them with the ones you have.
The portion of code that set the marker ( included the position) is this
var yourLat = 45.2323; // is only sample value
ver yourLng = 14.1818; // is only sample value
var marker = new google.maps.Marker({
position: new google.maps.LatLng(yourLat, yourLng),
map: map,
title: 'your title',
icon: '/image/cam.png'
});
You must assign the coord in google map notation so if you haven't this coord use google maps and click the point you desise. the coord appear in a box
Related
I have a map with several markers where the location comes from firebase up to that point, all right. The problem is when the possiblity of the marked update it to create a new marker rather than deletes the old one.
I have already researched here on the site but none answered the question.
Either delete all or only one at a time.
That is why I am opening this new question. Thank you all right away.
<?php
mysql_select_db($database_vpt2, $vpt2);
$query_onlines = "SELECT * FROM motoristas WHERE `online` = 1";
$onlines = mysql_query($query_onlines, $vpt2) or die(mysql_error());
$row_onlines = mysql_fetch_assoc($onlines);
$totalRows_onlines = mysql_num_rows($onlines);
?>
<script type="text/javascript">
var markers = [];
function initMap() {
var myLatLng = {lat: -5.079166, lng: -42.812019};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: myLatLng
});
<?php do { ?>
var adaRef = firebase.database().ref("local/<?php echo $row_onlines['id_motorista']; ?>");
adaRef.on("value", function(snapshot) {
var rodar = parseInt(snapshot.val() .giro);
var lat1 = snapshot.val() .latitude;
var lng1 = snapshot.val() .longitude;
var myLatLng = {lat: lat1, lng: lng1};
var image = '../icon/marker.png';
var marker = new google.maps.Marker({
id: <?php echo $row_onlines['id_motorista']; ?>,
position: myLatLng,
map: map,
title: 'OK',
icon: image,
});
markers.push(marker);
});
<?php } while ($row_onlines = mysql_fetch_assoc($onlines)); ?>
}
</script>
You can update the marker by keeping the reference of markers in an array. Then update it something like below.
var myNewLatlng = new google.maps.LatLng(-2.363882,131.044922);
marker.setPosition(myNewLatlng);
Reference: https://developers.google.com/maps/documentation/javascript/3.exp/reference#Marker
I'm trying to find out a way which i can have a dynamic center point, rather than have it static, Is there a way i can do this via the bounds method ?
For now i am getting the dynamic location but when the map loads, it is showing the static location, This new google.maps.LatLng(37.775196, -122.419204);
Which i want to point my dynamic location when the map loads.
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<?php
$res = $con->query("SELECT mrk_lat , mrk_lng FROM `marker_info` ORDER BY mrk_id DESC
LIMIT 1 ");
$mrk_cnt = 0;
while ($obj = $res->fetch_object()){
$lat[$mrk_cnt] = $obj->mrk_lat; // save the lattitude
$lng[$mrk_cnt] = $obj->mrk_lng; // save the longitude
$mrk_cnt++; // increment the marker counter
}
$res->close();
?>
<script type='text/javascript'>
var point;
var mrktx;
function load() {
addTo = 0;
var latlng = new google.maps.LatLng(37.775196, -122.419204);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
<?php
for ($lcnt = 0; $lcnt < $mrk_cnt; $lcnt++){
echo "var point$lcnt = new google.maps.LatLng($lat[$lcnt], $lng[$lcnt]);\n";
echo "var marker$lcnt = new google.maps.Marker({position: point$lcnt, map: map});\n";
}
?>
}
</script>
</head>
<body onload='load()'>
<div id="map_canvas" style="width: 1440px; height: 669px; margin: 0 0 0 0;"></div>
</div>
Just put your PHP variables containing the location using the echo shorthand:
new google.maps.LatLng(<?=$lat[$mrk_cnt]?>, <?=$lng[$mrk_cnt]?>)
Or in your code at the end:
echo "var point$lcnt = new google.maps.LatLng(" . $lat[$lcnt] . "," . $lng[$lcnt] . ");\n";
This is my first post so i'm sorry if it has been asked before.
I have a form users fill out on mobile devices which captures there longitude and latitude using JavaScript geolocation. this isn't always the most accurate so I am trying to combine geolocation and google map draggable pin.
So the user opens the page, geolocation enters the current lon and lat in the script below, if its wrong they can then drag the pin to the right location which updates the text fields.
I have tried every thing and have had mixed results...if someone could help me out that would be great.
I hope this makes sense...if not im happy to explain more
The script below enables you to drag the pin and updates the two text field with the lon and lat.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input type="text" id="latitude" placeholder="latitude">
<input type="text" id="longitude" placeholder="longitude">
<div id="map" style="width:500px; height:500px"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var $latitude = document.getElementById('latitude');
var $longitude = document.getElementById('longitude');
var latitude = 50.715591133433854
var longitude = -3.53485107421875;
var zoom = 7;
var LatLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: LatLng,
panControl: false,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: 'Drag Me!',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLng = marker.latLng;
$latitude.value = latLng.lat();
$longitude.value = latLng.lng();
});
}
initialize();
</script>
</body>
</html>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
function initialize() {
var map;
var position = new google.maps.LatLng(50.45, 4.45); // set your own default location.
var myOptions = {
zoom: 15,
center: position
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
// We send a request to search for the location of the user.
// If that location is found, we will zoom/pan to this place, and set a marker
navigator.geolocation.getCurrentPosition(locationFound, locationNotFound);
function locationFound(position) {
// we will zoom/pan to this place, and set a marker
var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// var accuracy = position.coords.accuracy;
map.setCenter(location);
var marker = new google.maps.Marker({
position: location,
map: map,
draggable: true,
title: "You are here! Drag the marker to the exact location."
});
// set the value an value of the <input>
updateInput(location.lat(), location.lng());
// Add a "drag end" event handler
google.maps.event.addListener(marker, 'dragend', function() {
updateInput(this.position.lat(), this.position.lng());
});
}
function locationNotFound() {
// location not found, you might want to do something here
}
}
function updateInput(lat, lng) {
document.getElementById("my_location").value = lat + ',' + lng;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<div id="map-canvas"></div>
Location:<br>
<input id="my_location" readonly="readonly">
You can get the user location from the navigator.geolocation:
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
latPosition = position.coords.latitude;
longPosition = position.coords.longitude;
});
Then you can use these values to fill in your coordinates inputs and/or to place a marker on the map, as in my demo below.
JSFiddle demo
i have a problem with placing multiple marker in google map.here is my code.it display only one marker during page reloading and when page is complettly load then map is not display.
javascript code:
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
function initialize(lat,lon)
{
var myCenter=new google.maps.LatLng(lat,lon);
var mapProp = {
center:myCenter,
zoom:9,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
php code:
<?php
require_once 'geocode.php';
$addarray=array(0=>'a, ahmedabad,india',1=>'b,ahmedabad,india');
foreach($addarray as $add)
{
// define the address and set sensor to false
$opt = array (
'address' => urlencode($add),
'sensor' => 'false'
);
// now simply call the function
$result = getLatLng($opt);
// if status was successful, then print the lat/lon ?
if ($result['status']) {
echo '<pre>';
?>
<script>
initialize(<?php echo $result['lat'];?>,<?php echo $result['lon'];?>);
</script>
<?php
echo '</pre>';
}
}
?>
here first i got lat and lon according to address then i called javascript function to place marker.but something is missing or create a problem.
thanks in advance.
Thanks #Tudor Ravoiu for your help. it is solved by changing few things.
i have created array in json format in php and pass it to javascript.
<?php
require_once 'geocode.php';
$addarray=array(0=>'a,ahmedabad,india',1=>'b,ahmedabad,india',2=>'c,ahmedabad,india');
$lat1=array();
foreach($addarray as $add)
{
// define the address and set sensor to false
$opt = array (
'address' => urlencode($add),
'sensor' => 'false'
);
// now simply call the function
$result = getLatLng($opt);
// if status was successful, then print the lat/lon ?
if ($result['status'])
{
array_push($lat1,array($result['address'],$result['lat'],$result['lon']));
}
}echo json_encode($lat1);
?>
javascript code:
<script type="text/javascript">
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
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
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
You have to set the array as a global var. Also notice that markers_array is an object that contain all the markers latitudes and longitudes and also other data if you want to initialize an infowindow also.
var markers;
var map;
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
for(i=0;i<markers_array.length;i++){
addMarker(markers_array[i].lat,markers_array[i].long);
}
function addMarker(lat,lng) {
var myLatlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
map: map,
position: myLatlng,
name: zip
});
markers.push(marker);
}
LATER EDIT:
Here is an example of the marker array in json format:
[
{
"name":"Marker 1 Italy",
"lat":"46.027482",
"long":"11.114502"
},
{
"name":"Marker 2 France",
"lat":"48.019324",
"long":"3.555908"
},
{
"name":"Marker 3 Spain",
"lat":"40.329796",
"long":"-4.595948"
}
]
I am using google maps api to place markers on a map. The gps coordinates of the markers are stored in a mySQL database. I have been able to create the markers however the locations will constantly changing so I was wondering how I would go about updating the markers' locations so that the markers will move across the map. Here is my code so far:
<!DOCTYPE html>
<html>
<head><title>Map</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<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(36.9947935, -122.0622702);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var image = new google.maps.MarkerImage('busIcon.png',
// The image size
new google.maps.Size(44, 46),
// The origin
new google.maps.Point(0,0),
// The anchor
new google.maps.Point(22, 23));
var shadow = new google.maps.MarkerImage('busIcon_shadow.png',
new google.maps.Size(58, 46),
new google.maps.Point(0,0),
new google.maps.Point(22, 23)
);
var shape = {
coord: [1, 1, 1, 45, 43, 45, 43 , 1],
type: 'poly'
};
var markers = [
<?php
// Make a MySQL Connection
mysql_connect("**********", "**********", "**********") or die(mysql_error());
mysql_select_db("matsallen") or die(mysql_error());
//Get number of rows
$result = mysql_query
(
'SELECT COUNT(*) FROM busTrack AS count'
)
or die(mysql_error());
$row = mysql_fetch_array( $result );
$length = $row["COUNT(*)"];
for ($count = 1; $count <= $length; $count++) {
//Get data from MySQL database
$result = mysql_query
(
'SELECT * FROM busTrack WHERE busID = '.$count
)
or die(mysql_error());
// store the record of the "busTrack" table into $row
$row = mysql_fetch_array( $result );
// Echo the data into the array 'markers'
$output = '{id: "Bus '.$row[busID].'", lat: '.$row[lat].', lng: '.$row[lon].'}';
if ($count != $length) {
$output = $output.',';
};
echo $output;
};
?>
];
for (index in markers) addMarker(map, markers[index]);
function addMarker(map, data) {
//create the markers
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.id,
icon: image,
shape: shape,
shadow: shadow
});
//create the info windows
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.id;
content.appendChild(title);
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);
});
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:75%; height:75%; margin:10%; allign:center;"></div>
</body>
</html>
To change the location of a marker, call setPosition() on that marker:
marker.setPosition(new google.maps.LatLng(newLat,newLng);
To do this, you will need to save all your markers in an array. Perhaps something like this would work:
var myMarkers = new Array();
for (index in markers) {
myMarker[ markers[index]['id'] ] = addMarker(map, markers[index]);
}
function addMarker(map, data) {
//create the markers
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.id,
icon: image,
shape: shape,
shadow: shadow
});
//create the info windows
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.id;
content.appendChild(title);
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);
});
return marker;
}
Then, when the position of a marker needs to change, hopefully you know the bus ID and can just call:
myMarkers['Bus 47'].setPosition(new google.maps.LatLng(newLat,newLng);
I didn't test the above code so there may be small syntax errors or something, but it should give you the idea.