This question already has an answer here:
google maps move marker with lat/lng from ajax success returned data
(1 answer)
Closed 8 years ago.
I'm having a problem with the maps markers. The map and marker load fine on the inital pageload. But when I try to update the marker location it simply disappears. The Alert window gives the correct coördinates. What am I doing wrong here?
Code:
<script>
var myCenter=new google.maps.LatLng(<?php echo $loc; ?>);
function initialize()
{
var mapProp = {
center:new google.maps.LatLng(<?php echo $loc; ?>),
zoom:15,
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);
setInterval(function(){
jQuery.get('loc.php?v=<?php echo $_GET['voertuignummer'];?>', function(data) {
alert(data);
position = new google.maps.LatLng(data);
marker.setPosition(position);
map.setCenter(position);
});
}, 15000);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
function(data) {
alert(data);
position = new google.maps.LatLng(data);
..
Looks very wrong; data is a string, probably containing "lat, lng", which google.maps.LatLng cannot be initialized with. new google.maps.LatLng requires a pair of type number in the arguments, like (number, number).
Do this instead :
data = data.split(',');
position = new google.maps.LatLng(parseFloat(data[0]), parseFloat(data[1]));
Related
This question already has answers here:
multiple markers on google maps from xml file
(2 answers)
Closed 7 years ago.
This is an XML entry and it takes geolocation from PHP form. I want to display those values as a map in HTML:
<entries>
<entry>
<name>Anny</name>
<email>anny1#hotmail.com</email>
<place>Fridays</place>
<comment>Very Good</comment>
<food>Jack Daniels Burger</food>
<kitchen>American</kitchen>
<rating>5</rating>
<latitude>34.7618259</latitude>
<longitude>33.0283905</longitude>
<picture/>
</entry>
</entries>
how are you generating this XML? I am assuming you use php to generate it.
This here will do it via JavaScript, assuming you're using google-maps API.
maybe this can get you started:
var xml = "your xml file"
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = entries[i].getAttribute("name");
var email = entries[i].getAttribute("email");
var place ..... an so on
var lat = entries[i].getAttribute("latitude");
var lng = entries[i].getAttribute("longitude");
//the creation of point
point = new google.maps.LatLng(
lat,
lng);
//create actual marker
marker = new google.maps.Marker({
map: map,
position: point,
});
to create the info window:
infoWindow = new google.maps.InfoWindow;
var html = name + " " + email + ' ' place ; //+ ... whatever else
bindInfoWindow(marker, map, infoWindow, html);
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(html);
infoWindow.open(map, marker, html);
map.setCenter(marker.getPosition()); // this will center the map on the clicked marker
});
}
hopefully some of this can help
You want to show these LatLong points as markers, I assume. Here is how to do that in google maps.
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
See more at https://developers.google.com/maps/documentation/javascript/markers
Similarly you can do it in mapbox like this
L.mapbox.featureLayer({
// this feature is in the GeoJSON format: see geojson.org
// for the full specification
type: 'Feature',
geometry: {
type: 'Point',
// coordinates here are in longitude, latitude order because
// x, y is the standard for GeoJSON and many formats
coordinates: [
-77.03221142292,
38.913371603574
]
}).addTo(map);
I'm using Javascript to render an embedded Google Map canvas on my website.
The inputs to the rendering are lat/lng coordinates that are retrieved from a database. However, if lat/lng returns null, the map will render based on the corresponding address string retrieved from the database. The following script always renders correctly for lat/lng coordinates inputs, but doesn't work for address input. Strangely, when I refresh the page multiple times, the address input would work randomly. I'm trying to cut out this randomness. Think I'm pretty close but I can't seem to find the missing link.
Note: if lat/lng is null, a default value is applied to $lat and $lng so it doesn't mess up the JS below.
I would appreciate if anyone could tell me what's wrong with the below code that's causing the random rendering of address strings.
var map;
var marker;
var geocoder;
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var estLatLng = new google.maps.LatLng( <? php echo $lat; ?> , <? php echo $lng; ?> );
var mapOptions = {
center: estLatLng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
streetViewControl: true,
scrollwheel: false
}
map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: estLatLng,
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title: "<?php echo $name;?>"
});
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
<? php
} ?>
$(".navbar").load("navbar.html", function() {
$("#navbarrestaurants").addClass("active");
});
$(document).ready(function() { <? php
if ($calcAddress) { ?> // this chunk of code is not loaded if lat/lng is not null
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': "<?php echo $address;?>",
'componentRestrictions': {
country: 'Singapore'
}
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
}); <? php
} ?>
});
I believe your problem is that the code in $(document).ready is being executed before that in your initialize function (listening for window load). The load event is called once the page is completely loaded, including images, etc, while everything in your document ready block is called slightly earlier when the DOM is ready.
Because it is executed sooner, and acting upon variables like map, that haven't been set up yet by the initialize function, the code in your geocoding callback is probably causing errors when it tries to alter the map center and set marker coords.
Try executing your geocoding code after the map is initialized. ie: wrap it in its own function and call it at the end of the initialization function.
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var estLatLng = new google.maps.LatLng( <? php echo $lat; ?> , <? php echo $lng; ?> );
var mapOptions = {
center: estLatLng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
streetViewControl: true,
scrollwheel: false
}
map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: estLatLng,
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title: "<?php echo $name;?>"
});
codeAddress();
}
ex: http://jsfiddle.net/j7pb7w3d/2/
This isn't great however, as the map starts with its default center, then visibly jerks a second later to the new address.
Instead you could determine whether or not geocoding is necessary first, and do this before the map is loaded, then use the result to set the map center and marker when the map is first created. Ex: http://jsfiddle.net/qsefxu5q/2/
Note these examples are hardly perfect and will need to be changed for your purposes. Hopefully they give you some ideas.
Hello I am learning Google Map API from w3schools. I am new to JS and want to assign location.lat() and location.lng() to JavaScript variables. This is the copied code of tutorials. I am trying to assign the values as;
var latid=location.lat(); but I think lat() is returning nothing.
I have to save coordinates in database. If it is the wrong approach then please tell me what can I do to save lnglat coordinates in my database.
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=mykeyishidden&sensor=false"></script>
<script>
var map;
var myCenter=new google.maps.LatLng(51.508742,-0.120850);
function initialize() {
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map,marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
I see you are trying to access location through location.lat() but do not see anything on location on your entire script. I was expecting to see something like
google.maps.GeocoderGeometry.location
instantiated somewhere.
For your purpose, I think it is better to try the following if it is what you meant:
google.maps.LatLng.lat() // Returns latitude
google.maps.LatLng.lng() // Returns longitude
I ran your page and looked into the Console.
In the placeMarker(location), location has these attributes.
A: -1.8017578125
k: 49.03786794532644
Your lat() and lng() are actually returning values, not zero! So, for example, if you needed to store these in use somewhere else in your program, your code would have these things added...
<script>
var map;
var myCenter=new google.maps.LatLng(51.508742,-0.120850);
var myLatLng;
var myLatLngs[];
...
function placeMarker(location) {
...
myLatLng = {lat:location.lat(),lng:location.lng()};
console.log("Lat: " + myLatLng.lat + " Lng: " + myLatLng.lng);
myLatLngs.push(myLatLng);
infowindow.open(map,marker);
}
...
Now you've got myLatLng which stores the latitude and longitude, myLatLngs which is an array of every time the user clicks and stores these coordinates in order, and a console.log to display it to you to confirm in the console.
If you don't know how to access the browser console by looking at this thread: https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
I am trying to update marker on google map for every x seconds based on the data returned from a AJAX call. The Ajax function is called for every x seconds but the marker is not shown. Below is the JavaScript I wrote. Anyone know the reason? Thanks.
<script type="text/javascript">
var map
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(1.32643, 103.79426),
zoom: 11
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
//Ajax call to get position
function set_center() {
var feedback = $.ajax({
type: 'GET',
url: 'get_gps_position',
success: function (data) {
console.log(data);
if (data['gps_position_longitude'] != null && data['gps_position_latitude'] != null ) {
var latlng = new google.maps.LatLng(data['gps_position_longitude'], data['gps_position_latitude']);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"Hello World!"});
};
},
error: function(data) {
$("#result").html(data);
console.log(data)
}
});
}
setInterval(set_center, 10000);
</script>
Assuming that the request runs as expected and returns a valid JSON:
var latlng = new google.maps.LatLng(data['gps_position_longitude'], data['gps_position_latitude']);
A google.maps.LatLng expects the arguments to be in the order latitude, longitude , not longitude,latitude .
Furthermore: instead of creating new markers on each request you better create a single marker and use setPosition() to update the position.
Additionally: to ensure that the marker is visible inside the viewport also set the center of the map to latlng
Try use javascript to alert a message with the new marker's position to see if it really gets updated in the background. If it dose, then its to do with refreshing the dom or something.
EDIT: It now works, but does not load if the user does not allow or have location-based services. See accepted answer comment for jsfiddle example.
I've looked through a few tutorials and questions but I can't quiet understand what's happening (or in this case, not happening). I'm loading my map when the user clicks a link. This loads the map with the users current location in the center, and a marker at the users location. However, any markers outside of the if (navigation.location) don't seem to load. Below is my current code:
function initialize() {
// Check if user support geo-location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var userLat = position.coords.latitude;
var userLong = position.coords.longitude;
var mapOptions = {
zoom: 8,
center: point,
mapTypeId: google.maps.MapTypeId.HYBRID
}
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Place a marker
new google.maps.Marker({
position: point,
map: map,
title: 'Your GPS Location'
});
});
} else {
var userLat = 53;
var userLong = 0;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(userLat, userLong),
mapTypeId: google.maps.MapTypeId.HYBRID
}
// Place a marker
new google.maps.Marker({
position: point,
map: map,
title: 'Default Location'
});
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
<?
for ($i = 0; $i < sizeof($userLocations); $i++) {
?>
var userLatLong = new google.maps.LatLng(<? echo $userLocations[$i]['lat']; ?>, <? echo $userLocations[$i]['long']; ?>);
new google.maps.Marker({
position: userLatLong,
map: map,
title:"<? echo $userLocations[$i]['displayName'] . ', ' . $userLocations[$i]['usertype']; ?>"
});
<?
}
?>
}
function loadMapScript() {
if (typeof(loaded) == "undefined") {
$("#showMap").css("display", "none");
$("#showMapLink").removeAttr("href");
$("#map").css("height", "600px");
$("#map").css("width", "600px");
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=MY_API_KEY&sensor=true&callback=initialize";
document.body.appendChild(script);
loaded = true;
} else {
alert("Map already loaded!");
}
}
loadMapScript() is called when the user clicks a link. The php for loop loops through a pre-created array with all the information.
I'm guessing I don't fully understand it, as when if I put:
var userLatLong = new google.maps.LatLng(53, 0);
new google.maps.Marker({
position: userLatLong,
map: map,
title:"Title"
});
into the console (Google Chrome), I get the error:
Error: Invalid value for property <map>: [object HTMLDivElement]
I don't, however, get any errors otherwise. Any help would be much appreciated! :)
navigator.geolocation.getCurrentPosition() is asynchronous.
Reorganize your code like this:
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.HYBRID
}
function initialize() {
// Check if user support geo-location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
makeMap(position.coords.latitude, position.coords.longitude, 'Your GPS Location');
});
} else {
makeMap(53, 0, 'DefaultLocation');
}
}
function makeMap(lat, lng, text) {
var point = new google.maps.LatLng(lat, lng);
mapOptions.center = point;
map = new google.maps.Map(document.getElementById("map"), mapOptions);
new google.maps.Marker({
position: point,
map: map,
title: text
});
<?php for ($i = 0; $i < sizeof($userLocations); $i++): ?>
var userLatLong = new google.maps.LatLng(<? echo $userLocations[$i]['lat']; ?>, <? echo $userLocations[$i]['long']; ?>);
new google.maps.Marker({
position: userLatLong,
map: map,
title:"<? echo $userLocations[$i]['displayName'] . ', ' . $userLocations[$i]['usertype']; ?>"
});
<?php endforeach ?>
}
Also, consider bootstraping the $userLocations into a JavaScript variable like this:
var userLocations = <?php print json_encode($userLocations) ?>;
Then execute your for loop in JavaScript, instead of mixing languages.
Have you tried:
var map = null;
function initialize() { ... }
and then changing the code inside:
map = new google.maps.Map( ... ); //make this the first line
if (navigator.geolocation) {
// Change the code from:
var map ...
// to:
map ...
You just reference the map directly (without the var) everywhere else, so that should work.
Change:
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
To:
map = new google.maps.Map(document.getElementById("map"), mapOptions);
Because of var, your map variable is tied the the scope of initialize(). Removing it will set it as the global map variable (or window.map), making it available outside of the initialize() function.
What's happening is you have an HTML element <div id="map">. In many browsers, global variables are created from html element ids, so map equals document.getElementById('map').
Edit: Actually, this only explains your problem in the Chrome console. You need to set map before trying to attach markers to it, as you do within if (navigator.geolocation) {}. This also explains why none of the user location markers are being placed. The code to place them runs before initialize(). Put this code either within initialize or within its own function, and call that function from initialize.
It looks like you're creating the marker, but not doing anything with it. Try changing your new Marker to look like this:
var marker = new google.maps.Marker({
position: point, // this won't actually work - point is out of scope
title: 'Your GPS Location'
});
marker.setMap(map);
Edit: Make sure the point is inside the map!
var bounds = new google.maps.LatLngBounds();
bounds.extend(point);
map.fitBounds(bounds);