Changing javascript in google maps doesn't update it? - javascript

I am trying to make an AJAX map Google map, where the place markers update but not the map.
I have an ajax setup with a settimeout function, which returns new javascript. When the new javascript is loaded into my HTML, the changes do not reflect on my google map.
When I go into the firefox inspector and try and manipulate the javascript, (to try and change marker GPS coordinates), nothing happens to the map, and the points are still the same. Why does that not affect the map?
I have looked at several links to try and help me, but none of them explain the logic behind the javascript.
My PHP script returns javascript in plain text. But when these get
added to the HTML, The google map does not change and looks like it
needs to be re initialized before it recognizes new javascript?
Can someone explain how I should update the javascript, so the map re-centers on the newest marker and places the newest marker without refreshing the page / re initializing the map?
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: -20.530637, lng: 46.450046}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
new google.maps.LatLng("-21.530637,46.450046),
new google.maps.LatLng("-22.530637,46.450046),
]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'content.php',
type:'POST',
success:function(results) {
locations=results;
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,5000);
</script>
My "content.php" file. returns more google maps LatLng markers in plain text.
so PHP output is:
new google.maps.LatLng("-23.530637,46.450046"),
new google.maps.LatLng("-24.530637,46.450046"),
new google.maps.LatLng("-25.530637,46.450046"),
new google.maps.LatLng("-26.530637,46.450046")

I would like to summary the behavior of your ajax map:
Initialize map (probably with a set of predefined locations)
Repeatedly call content.php to retrieve new update of markers
Draw new markers to your map
The problem is that your code that handles ajax result doesn't do any map manipulation. In fact, it has to update the variable locations with new location set. Then create new markers with updated list of locations, then call MarkerCluster to apply them.
I created a fiddle to demonstrate it: https://jsfiddle.net/anhhnt/paffzadz/1/
What I did is extract the marker creating part from initMap, so that it can be called multiple times after locations is updated.
function updateMarker () {
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
};
function initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});
updateMarker(map);
};
var locations = [
{lat: -31.563910, lng: 147.154312},
{lat: -33.718234, lng: 150.363181},
{lat: -33.727111, lng: 150.371124}
]
function refresh_div() {
jQuery.ajax({
url:'/echo/json/',
type:'POST',
data: {
json: JSON.stringify([
{lat: -42.735258, lng: 147.438000},
{lat: -43.999792, lng: 170.463352}
])
},
success:function(results) {
locations.concat(results);
updateMarker();
}
});
}
t = setInterval(refresh_div,5000);
Hope it helps.

Perhaps you have simple syntax error in your code - missing closing double quote:
new google.maps.LatLng("-23.530637,46.450046"),
...
..or better - remove first double quote:
new google.maps.LatLng(-23.530637,46.450046),
...

Related

adding URL to map marker in Marker Cluster google map API

So basically what I am trying to do is have a map cluster and once you click into the clusters and click on the individule map markers you will be linked off to a different page on my website.
this is what i have so far. but i cant seem to pull the URLS through.. into different markers.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -39.3642, lng: 164.0444318}
});
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
url: "http://travelpark.co.nz" //Will be different for each marker
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: -37.7862985, lng: 175.2773836},
{lat: -37.8011434, lng: 174.871265}
]
google.maps.event.addListener(markers, 'click', function() {
window.location.href = this.url;
});
The event listener at the bottom doesnt work.. i cant seem to figure this out. any help would be appreciated
Assign listener to each marker object not to the array. Use your map function itself to avoid 2 for loops:
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position: location,
url: "http://travelpark.co.nz" //Will be different for each marker
});
google.maps.event.addListener(marker, 'click', function(){
window.location.href = this.url;
});
return marker;
});

How can I change marker position eventually in google maps api?

I have a problem with google maps api, when I change the marker position constantly, this leave a trace on map and I need move the marker without leaving a trace.
I actually get the latitude and the longitude from a database in firebase and need represent the route of a car.
var mapOptions = {
center: new google.maps.LatLng(20.615977, -103.339358),
zoom: 12
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
firebase.database().ref('route').on('value', function(data) {
var start = new google.maps.Marker({
position: {lat: latitud, lng: longitud},
map: map,
icon: '../icon/car.png'
});
var myLatlng = new google.maps.LatLng(data.val().latitude, data.val().longitude);
start.setPosition(myLatlng);
start.setMap(map);
});
You're creating a new marker in every event. Instead, create the marker before the event handler (and call setMap there), and in your handler, just do setPosition() to the data's new lat/lng.

HTML/JS - Google Maps v3 - select/remove marker by id from external link

I'm new to google maps and javascript . I'm trying to interact with the map using external links/lists.
My main problem is that i'm unable to select the marker on the map with its id.
I don't want to put all markers in a list/array and iterate over them since i don't know how many there will be at any point.
I simply want to select them by their id and work with them such as opening infowindow , removing them etc...
in my changeIcon() function , i tried some ways but none worked so far .
<html>
....
<div id="mapview"></div>
<a class="test-link" onmouseover="changeIcon()">Link</a>
<script>
function changeIcon()
{
//marker = map.selectMarker("4");
//marker = markers[4];
//infowindow.open(map,marker);
//$("#mapview").map.removeMarker(4);
}
var map = new google.maps.Map(document.getElementById('mapview'),
{
center: {lat: 44.540, lng: -78.546},
zoom: 16
});
function initMap()
{
var marker = new google.maps.Marker({
position: userPosition,
map: map,
id: 4
});
}
</script>
</html>
............................................
There is no API to get marker from map. ref:
"https://developers.google.com/maps/documentation/javascript/reference"
I think you dont want to use array because id will never match the index. So I suggest using dictionary:
var markers = {}; // "{}" to specify dictionary instead of "[]" to specify array
when you create marker, you add it to dictionary:
markers[4] = marker; // 4 is the id
when you want to get it:
var currentMarker = markers[4];

map as div background - Google Maps API

I'm using for a while following javascript code to load google map as DIV background.
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
function init() {
// Basic options for a simple Google Map
// For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 15,
// The latitude and longitude to center the map (always required)
center: new google.maps.LatLng(54.549047, 18.443433), // New York
// How you would like to style the map.
// This is where you would paste any style found on Snazzy Maps.
styles: [ { featureType:"all", elementType:"all", stylers:[ { invert_lightness:true }, { saturation:10 }, { lightness:30 }, { gamma:0.5 }, { hue:"#1C705B" } ] } ]
};
// Get the HTML DOM element that will contain your map
// We are using a div with id="map" seen below in the <body>
var mapElement = document.getElementById('map');
// Create the Google Map using out element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
}
works perfectly. But when I've tried to load there a marker which will point to my location, it crashes. Any ideas what will be the proper placement of such? I assume this is the proper code (which doesn't work..):
var myLatlng = new google.maps.LatLng(54.549047, 18.443433);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
thanks for the help!

Google maps: how to find all of the markers inside the map by using gmaps.js

I have created some markers by using addMarker() of gmaps.js:
var lat= new Array();
var lng= new Array();
var title= new Array();
lat[0]=...
lng[0]=...
title[0]=...
...
for(i=0;i<lat.lenth;i++){
map.addMarker({
lat: lat[i],
lng: lng[i],
title: title[i],
});
}
Now, I want to only get the markers that inside the current displayed map and display the lists of site to the table. How can I do that? Is there any API from gmaps.js can implement with ease?
Thanks for any help!
You need to get the map's bounds, and then see if that bounds contains each marker.
var bounds = map.getBounds();
for (var i=0;i<lat.length;i++) {
var latlng = new google.maps.LatLng(lat[i], lng[i]);
map.addMarker({
lat: lat[i],
lng: lng[i],
title: title[i],
});
if (bounds.contains(latlng)) {
// add the details into an array here. After the loop, output the contents to a div
}
}

Categories

Resources