Google Maps Move Marker with Lat/Lng from Ajax Success Returned Data

google maps move marker with lat/lng from ajax success returned data

The google.maps.LatLng constructor takes two numbers for arguments. This won't work:

var newLatLang = new google.maps.LatLng(newCoords);

You need to convert newCoords into two numbers.

Convert String to latlng google maps

Convert “[52.43242, 4.43242]” to google LatLng

How do I get a pin on Google Maps using location from a variable?

Google map on ajax success

Of course I can make my comment above as an answer.

You can also listen to the "google-maps-ready"-event in the script-url by using the callback-parameter (HTML):

<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?libraries=geometry,places&callback=initialize">
</script>

JS:

// In this way you have to define a function called initialize which should be defined globally otherwise it can not be found by the google-library.

// unfortunately this map-variable is defined globally here but you can also wrap the whole code below by using an IIFE.
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
// you might set a center here or wait untill you have got some markers fetched via ajax, you can then use the first/last or some other marker respecetive it's position(lat,long) to set as "starting point"
//center: {lat: LAT, lng: LONG }
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}

// Although I have no access to your website to test this code below, it might be done in this way:
$(document).ready(function () {
$('.selectCity').change(function () {
var city = $(this).val();
$.ajax({
type: 'GET',
url: '/riders/location/track',
data: {
'city': city
},
success: function (data) {
var positions = [];
//Get Locations and push it to lat and lng
// you can also use just one array to insert all locations and "labels" into
$.each(data, function (index, value) {
$.each(value, function (index1, value1) {
console.log(value1.rider_location.lat);
positions.push({
lat: value1.rider_location.lat,
lng: value1.rider_location.lng,
content: 'Rider' // do you get some text with each location?
});
});
});
// set "starting point" afterwards
map.setCenter({
lat: positions[0].lat,
lng: positions[0].lng
});
var infowindow = new google.maps.InfoWindow();
var marker,
i;
for (i = 0; i < positions.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(positions[i].lat, positions[i].lng),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(positions[i].content);
infowindow.open(map, marker);
}
}) (marker, i));
}
}
});
});
});

Hope it helps!

Javascript: Google maps set marker latitude longitude every x seconds?

One option would be to use setInterval to periodically read the localStorage and set the marker position (creating the marker if it doesn't exist).

proof of concept fiddle

code snippet:

var map;var marker;
function initialize() { map = new google.maps.Map( document.getElementById("map_canvas"), { center: new google.maps.LatLng(37.4419, -122.1419), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP });}
function setLocalStorage() { var lat = document.getElementById('lat').value; var lng = document.getElementById('lng').value; localStorage.setItem('mylat', lat); localStorage.setItem('mylng', lng);}setInterval(function() { var lat = parseFloat(localStorage.getItem("mylat")); var lng = parseFloat(localStorage.getItem("mylng")); map.panTo({ lat: lat, lng: lng }); if (!marker || !marker.setPosition) { marker = new google.maps.Marker({ position: { lat: lat, lng: lng }, map: map }); } else { marker.setPosition({ lat: lat, lng: lng }); }}, 5000);google.maps.event.addDomListener(window, "load", initialize);
html,body,#map_canvas {  height: 100%;  width: 100%;  margin: 0px;  padding: 0px}
<script src="https://maps.googleapis.com/maps/api/js"></script><input id="lat" value="42" /><input id="lng" value="-72" /><input type="button" onclick="setLocalStorage();" value="click" /><div id="map_canvas"></div>

Update markers from Ajax Json array in google map when map is moved

    If I understand correctly, there are two thing you want to achieve here. 

1. when initialize the map, get json from server and add makers on it.
2. when bounds changes, get json and redraws all the maps.

You are very close, I would suggest you to reorganize your code.

1. you need a global array of marks, so you can remove makers from map for redrawing.

```
// set globals
var makers = []
// clear markers
function clearMaker (markers) {
markers.map(m => {m.setmap(null)})
}
```

2. seperate drawMarkers function
```
// drawMarkers
function drawMarkers(markerJson, markers, map, infowindow) {
clearMarkers(markers);
// your draw marker code
}
```

3. Your loadLocation

```
/*search location based on geoparams
geoparam: {
a: ne_lat,
b: ne_lng,
c: sw_lat,
d: sw_lng
}
*/

function loadLocations(geoparam)
{
return $.ajax({
type:'POST',
url: 'includes/newjson.php',
dataType: 'json',
data: geoparam
})
}
```
You can call loadLocation functions when initilize and bounds_changed and it returns a promise.

```
loadLocation(geoparams).then((data) => {
drawMarkers(data, markers, map, inforwindow);
}).catch(err => { console.log(error)});
```

Creating a marker for each lat,lng in the list Google Maps

Your problem is you're looping over your list of locations, creating a new map for each one. 200 markers is no problem, but 200 maps isn't very good. Move the code creating the map outside of the loop:

function setMap(locationList) {
locationObj = $.parseJSON(locationList);
var qMapTypeId = google.maps.MapTypeId.SATELLITE

mapOptions = {
zoom: 1,
center: myLatlng, // this line won't work yet
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}

map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

map.setTilt(45);
map.setHeading(0);
map.setMapTypeId(qMapTypeId);

for (i in locationObj) {
var LatLngPair = new google.maps.LatLng(locationObj[i]["Lat"], locationObj[i]["Lng"]);

var hItem = locationObj[i];
var qLat = parseFloat(hItem["Lat"]);
var qLong = parseFloat(hItem["Lng"]);

var myLatlng;
if (qLat != 0 && qLong != 0) {
myLatlng = new google.maps.LatLng(qLat, qLong);

var marker = new google.maps.Marker({
position: myLatlng,
map: map
});

google.maps.event.addListener(marker, "click", function(event) {

});
}

}
$("#map-canvas").show();
$("#divLoadingMessageMap").css("display", "none");
}

The only problem here is you're going to have to give a lat/lng to your map options, which you don't have yet. There's various clever ways you can do this after you've added the markers, or you may already know a lat/lng you can use.

Google Maps Marker Data

HA! I figured it out. "this" did it!

google.maps.event.addListener(newmarker, "click", function(mark) {
alert(this.hotspotid);
});


Related Topics



Leave a reply



Submit