This map is to track multiple markers in a single view. The markers have to be updated every 5 seconds from the server.
My infowindow disappears after each refresh. There is a json request every 5 seconds. when i click on the marker, the infowindow appears and is cleared as soon as during next json call. Can i devise a method/any solution to make it appear(dynamic) even after refreshing.
var map1;
function map1_initialize( )
{
setInterval(function() {
var lat=new Array();var lng=new Array();var latlng = [];
$.getJSON('web_services/latlong.php?option=4&user_id=<?php echo $user_id;?>', function(json) {
$.each(json.Result.Data,function(i,gmap){
lat[i]=gmap.latitude;
lng[i]= gmap.longitude;
latlng[i] = new google.maps.LatLng(lat[i], lng[i]);
/*google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(json.Result.Data[i].alias);
console.log(json.Result.Data[i]);
infowindow.open(map, marker);
}
})(marker, i)); */
if ( google.maps.BrowserIsCompatible( ) )
{
map1 = new google.maps.Map2( document.getElementById( 'map' ) );
map1.addControl( new google.maps.LargeMapControl3D( ) );
map1.addControl( new google.maps.MenuMapTypeControl( ) );
map1.setCenter( new google.maps.LatLng( 0, 0 ), 0 );
for ( var i = 0; i < latlng.length; i++ )
{
var marker = new google.maps.Marker( latlng[ i ] );
map1.addOverlay( marker );
}
var latlngbounds = new google.maps.LatLngBounds( );
for ( var i = 0; i < latlng.length; i++ )
{
latlngbounds.extend( latlng[ i ] );
}
map1.setCenter( latlngbounds.getCenter( ), map1.getBoundsZoomLevel( latlngbounds ) );
GEvent.addListener(marker, 'click', function() {
// When clicked, open an Info Window
//alert(gmap.alias);
marker.openInfoWindowHtml(gmap.alias);
});
//gmap.alias is the alias name for the marker-loading it via json response
}
});
});
}, 5000);
}
With lot of R&D, i found out the answer!!!Hope this might help somebody...
var json=[];
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
});
/*jQuery.extend({
getValues: function(url) {
var result = null;
$.getJSON('web_services/latlong.php?option=4&user_id=21', function(json) {
result = json;
});
return result;
}
});*/
jQuery.extend({
getValues: function(url) {
//setInterval(function() {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
result = data.Result.Data;
}
});
return result;
//},5000);
}
});
setInterval(function() {
var markers=$.getValues("web_services/latlong.php? option=4&user_id=21");console.log(markers);
// Define the list of markers.
// This could be generated server-side with a script creating the array.
/*var markers = [
{ lat: -33.85, lng: 151.05, name: "marker 1" },
{ lat: -33.90, lng: 151.10, name: "marker 2" },
{ lat: -33.95, lng: 151.15, name: "marker 3" },
{ lat: -33.85, lng: 151.15, name: "marker 4" }
];*/
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
title: data.alias
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.alias;
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);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
/* google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});*/
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.latitude, data.longitude));
}
map.fitBounds(bounds);
},5000);//call every of 5 secs.
}
Related
when map bound moved by user, make disappear old position markers and display new markers.
For an example you can check this map. Markers are moving every time bounds updated and clearing the old position markers. I am exactly trying to do this.
UPDATED 2
what I have done so far is right below. No errors but, still seeing all markers at once..?
data(){
return {
bounds:{},
map: {},
mapName: "map",
estates: [],
}
},
mounted() {
axios.get('/ajax').then((response) => {
this.estates = response.data
this.insertMarkers();
});
this.initMap();
},
methods: {
initMap: function() {
this.bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(34.652500, 135.506302),
);
var mapOptions = {
mapTypeId: 'roadmap',
center: new google.maps.LatLng(0, 0),
zoom: 8
};
let self = this;
this.map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
var boundsListener = google.maps.event.addListener((this.map), 'bounds_changed', function(event) {
self.getMarkers();
});
this.map.fitBounds(this.bounds);
},
getMarkers: function() {
let bounds = this.map.getBounds();
let southWest = bounds.getSouthWest();
let northEast = bounds.getNorthEast();
console.log(southWest);
axios.get('/ajax', {
params: {
fromLat: southWest.lat()-0.01,
toLat: northEast.lat()-0.01,
fromLng: southWest.lng()+0.01,
toLng: northEast.lng()+0.01,
}
}).then((response) => {
this.estates = response.data;
this.updateMarkers();
});
},
updateMarkers: function() {
google.maps.event.addListener(map, 'idle', function() {
var map = this.map;
var estates = this.estates;
let i = 0;
for (i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
}
this.markers = [];
for (i = 0; i < estates.length; i++) {
var position = new google.maps.LatLng(estates[i].lat, estates[i].lng);
var marker = new google.maps.Marker({
position: position,
map: map,
label: {
text:
estates[i].price.toString().length == 1 ?
estates[i].price.toString().replace("1", "未定") :
estates[i].price.toString() + "万",
color: '#fff',
},
icon: '/img/marker.png',
url: "/pages/" + estates[i].id,
});
this.markers.push(marker);
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
}
});
},
As I said in my comment, you can do it the other way around. Fetch only markers that are visible within the map viewport. You just need to reorganize your code a bit and modify your database query.
You need to pass a minimum and maximum latitude and longitude to your controller so that you can query the DB for markers between the given latitudes and longitudes. You can get these by getting your map bounds and extracting southwest and northeast lat/lng.
export default {
data() {
return {
bounds: {},
map: {},
mapName: "map",
estates: [],
markers: [] // Added markers array here
}
},
mounted() {
this.initMap(); // On "mounted" only call initMap
},
methods: {
initMap: function() {
//giving specific location of japan.
this.bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(34.652500, 135.506302),
);
var mapOptions = {
mapTypeId: 'roadmap',
center: new google.maps.LatLng(0, 0),
zoom: 5
};
this.map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
let self = this;
var boundsListener = google.maps.event.addListener((this.map), 'idle', function(event) {
self.getMarkers(); // When map is idle, get markers
});
this.map.fitBounds(this.bounds);
},
getMarkers: function() {
// Get current map bounds
let bounds = this.map.getBounds();
let southWest = bounds.getSouthWest();
let northEast = bounds.getNorthEast();
// Send request with min/max latitude and longitude to only fetch markers for that area
axios.get('/ajax', {
params: {
fromLat: southWest.lat(),
toLat: northEast.lat(),
fromLng: southWest.lng(),
toLng: northEast.lng(),
}
}).then((response) => {
this.estates = response.data;
this.updateMarkers();
});
},
updateMarkers: function() {
// Remove previous markers
for (let i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
}
// Reset markers array
this.markers = [];
// Add current markers
for (i = 0; i < estates.length; i++) {
var position = new google.maps.LatLng(estates[i].lat, estates[i].lng);
var marker = new google.maps.Marker({
position: position,
map: map,
icon: '/img/marker.png',
url: "/pages/" + estates[i].id,
});
// Push marker to markers array for future removal
this.markers.push(marker);
}
}
}
}
In your controller, you need to get the parameters you send with the axios request (fromLat, toLat, etc.)
public function ajax() {
// Here you need to retrieve the parameters sent by the axios request !
// And set them as $fromLat, $toLat, etc.
$data = \DB::table('allestates')
->where('lat', '>', $fromLat)
->where('lat', '<', $toLat)
->where('lng', '>', $fromLng)
->where('lng', '<', $toLng)
->get();
$response = response()->json($data);
return $response;
}
Untested, but that should work. You need to adapt some parts! Read my comments in the code as well.
Note: the bounds_changed event is triggered repeatedly when a user drags the map, so this way you are going to send a lot of requests to your database. Instead, you should probably prefer another event such as idle or delay the trigger of your ajax call somehow to reduce the number of queries.
You need to store old Value and compare with new one you need timeout function to update each time iterval ex window.setTimeout(insertMarkers,3000)
for(var i=0, len=res.length; i<len; i++) {
//Do we have this marker already?
if(markerStore.hasOwnProperty(res[i].driver_id)) {
markerStore[res[i].id].setPosition(new google.maps.LatLng({lat: parseFloat(res[i].lat), lng: parseFloat(res[i].lng)}));
} else {
marker = new google.maps.Marker({
position: {lat: parseFloat(res[i].lat), lng: parseFloat(res[i].lng)},
map:map
});
google.maps.event.addListener(marker, 'click', (function(marker, i,id) {
return function() {
console.log(id)
}
})(marker, i,id));
markerStore[res[i].id] = marker;
}
}
markerStore[estate.id] = marker;
}
});
UPDATE
mounted() {
.
.
.
this.initMap();
window.setTimeout(this.insertMarkers,3000)
},
methods: {
.
.
.
insertMarkers: function() {
var marker=[];
var markerStore = {};
this.estates.forEach((estate, index) => {
//Do we have this marker already?
if(markerStore.hasOwnProperty(estate.id)) {
markerStore[estate.id].setPosition(new google.maps.LatLng({lat: parseFloat(estate.lat), lng: parseFloat(estate.lng)}));
} else {
marker = new google.maps.Marker({
icon: '/img/marker.png',
position: {lat: parseFloat(estate.lat), lng: parseFloat(estate.lng)},
map:map
});
var es_id=estate.id;
google.maps.event.addListener(marker, 'click', (function(marker, index,es_id) {
return function() {
console.log(es_id)
window.location.href = "/pages/" + es_id;
}
})(marker, index,es_id));
markerStore[estate.id] = marker;
}
});
I have the following Ajax request on a select drop down change which simply gets the records from the controller, Loop through each one and get the latitude | longitude and pushes it to an array.
Then in the same ajax success i pass that lat and lng array to google map.
But the map doesn't shows up..
$(document).ready(function() {
$('.selectCity').change(function() {
var city = $(this).val();
$.ajax({
type: 'GET',
url: '/riders/location/track',
data: {
'city': city
},
success: function(data) {
var lat = [];
var lng = [];
//Get Locations and push it to lat and lng
$.each(data, function(index, value) {
$.each(value, function(index1, value1) {
console.log(value1.rider_location.lat);
lat.push(value1.rider_location.lat);
lng.push(value1.rider_location.lng);
});
});
//Google Map
google.maps.event.addDomListener(window, 'load', init);
function init() {
var locations = [
['Rider', lat, lng]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(lat, lng),
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][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));
}
}
}
});
});
});
Plus please suggest best practice also.
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!
I am new to Meteor and Javascript. I am creating a map that gives directions from your current location to a marker on the map. Everything seems to work except that I can't seem to call the calcRoute() function correctly. Or maybe it is defined in the wrong place.
I think I need some schooling on template helpers. Please tell me where I went wrong. Thanks.
var gmaps = {
// map object
map: null,
//direction services object
directionsService: null,
//direction services object
directionsDisplay: null,
//direction services object
stepDisplay: null,
markerArray: []
}
Template.map.helpers({
mapOptions: function() {
if (GoogleMaps.loaded()) {
if (!Geolocation.error()) {
pos = Geolocation.latLng();
}
return {
//center: new google.maps.LatLng(-25.2743, 133.7751),
center: new google.maps.LatLng(pos.lat, pos.lng),
zoom: 12,
scaleControl: false,
zoomControl: false,
mapTypeControl: false,
panControl: false,
rotateControl: true,
overviewMapControl: false,
streetViewControl: false,
};
}
},
calcRoute: function() {
//clear markers before calculating function
gmaps.clearMarkers();
console.log(this.markerArray);
// Retrieve the start and end locations and create
// a DirectionsRequest using BICYCLING directions.
var start = marker3.getPosition();
var end = document.getElementById('marketName').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.BICYCLING
};
// Route the directions and pass the response to a
// function to create markers for each step.
this.directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
this.directionsDisplay.setDirections(response);
gmaps.showSteps(response);
}
});
},
showSteps: function(directionResult) {
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_location,
map: map.instance
});
gmaps.attachInstructionText(marker, myRoute.steps[i].instructions);
this.markerArray[i] = marker;
}
},
attachInstructionText: function(marker, text) {
// Instantiate an info window to hold step text.
var stepDisplay = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'mouseover', function() {
// Open an info window when the marker is clicked on,
// containing the text of the step.
stepDisplay.setContent(text);
stepDisplay.open(map.instance, marker);
})
google.maps.event.addListener(marker, 'click', function() {
map.instance.setZoom(14);
map.instance.setCenter(marker.getPosition());
stepDisplay.open(map.instance, marker);
})
},
clearMarkers: function() {
// First, remove any existing markers from the map.
for (var i = 0; i < this.markerArray.length; i++) {
this.markerArray[i].setMap(null);
}
// Now, clear the array itself.
this.markerArray = [];
}
});
Template.map.onCreated(function() {
GoogleMaps.ready('map', function(map) {
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map.instance);
var marker1 = new google.maps.Marker({
position: new google.maps.LatLng(29.71739, -95.40183),
map: map.instance,
title: 'Rice U Farmers Market'
});
var infowindow1 = new google.maps.InfoWindow({
content: ''
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.setContent( '<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(calcRoute());">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
});
var marker2 = new google.maps.Marker({
position: new google.maps.LatLng(29.81063, -95.37999),
map: map.instance,
title: 'Canino\'s Produce'
});
var infowindow2 = new google.maps.InfoWindow({
content: 'Canino\'s Produce'
});
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map.instance, marker2);
});
var image = '/img/app/flag1.png'
var marker3 = new google.maps.Marker({
position: new google.maps.LatLng(pos.lat, pos.lng),
map: map.instance,
title: 'You are here',
icon: image
});
var rendererOptions = {
map: map.instance
}
this.directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// global flag saying we intialized already
Session.set('map', true);
})
});
You have to pass the name of the method that Meteor will call as a string;
Replace:
'<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(calcRoute());">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
with:
'<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(\'calcRoute\');">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
Im trying to load around 600 googlemap markers on page load using the function addMarker.
The page takes a lot of time to load.
Is there anything I can do to make it load faster while keep using the addMarker function?
Thanks.
var map
var myLatlng = new google.maps.LatLng(35.9531719,14.3712201);
var markerBounds = new google.maps.LatLngBounds();
var markers = {};
function HomeControl(controlDiv, map)
{
google.maps.event.addDomListener(zoomout, "click", function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 0)
{
map.setZoom(currentZoomLevel - 1);
}
});
google.maps.event.addDomListener(zoomin, "click", function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 21)
{
map.setZoom(currentZoomLevel + 1);
}
});
}
function initialize()
{
var googleMapOptions = {
center: new google.maps.LatLng(35.9531719,14.3712201),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
streetViewControl: false,
panControl: false,
draggable: true
};
map = new google.maps.Map(document.getElementById("map-canvas"), googleMapOptions);
google.maps.event.addListener(map, "idle", function() {
addMarker(latitude,longitude,id,'Title','url');
});
var homeControlDiv = document.createElement("div");
var homeControl = new HomeControl(homeControlDiv, map);
}
var infowindow = new google.maps.InfoWindow({
content: ""
});
function addMarker(lat,long,id,desc,url)
{
var myIcon = new google.maps.MarkerImage("/images/pips/"+id+".png", null, null, null, new google.maps.Size(28,38));
var myLatlng = new google.maps.LatLng(lat,long);
var marker = new google.maps.Marker({
map: map,
title: desc,
position: myLatlng,
icon: myIcon,
id: id
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('' + desc + '');
infowindow.setPosition(marker.getPosition());
infowindow.open(map, marker);
});
markers[id] = marker;
markerBounds.extend(myLatlng);
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map,marker);
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
You can use clustering, it joins neighbor markers into one, and expand only on zoom
You can do clustering in client side, as well as server side, depending the amount of markers...
I would suggest to use server clustering if amount is more than 4000, otherwise client should look fine
I am trying to update the location of a marker with out refreshing the whole page. I have tried to use setTimeout(function() however I am having no luck..
here is my code I have so far..
thanks in advance
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(35.66, -80.50),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "getjson.php",
'dataType': "json",
'success': function (data) {
json = data; } });
return json;})();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
here is my JSON output.
[{"lat":35.6606376,"lng":-80.5048653,"content":"bca"}, {"lat":42.6799504,"lng":-36.4949205,"content":"abc"}]
I would suggest using setInterval rather than setTimeout.
Here is some code that simulates an update via JSON in a fiddle, using your provided JSON with the required "description" member added for each marker:
var map = null;
var gmarkers = [];
var intervalNumber = 0;
setInterval(function () {
new Request.JSON({
url: '/echo/json/',
data: {
json: JSON.encode([{
"lat": 35.6606376 + (0.01 * intervalNumber),
"lng": -80.5048653 + (0.1 * intervalNumber),
"content": "bca",
"description":"first marker"
}, {
"lat": 42.6799504 + (0.01 * intervalNumber),
"lng": -36.4949205 - (0.1 * intervalNumber),
"content": "abc",
"description": "second marker"
}]),
delay: 3
},
onSuccess: function (response) {
update_map(response);
intervalNumber++;
}
}).send();
}, 5000);
update_map = function (data) {
var bounds = new google.maps.LatLngBounds();
// delete all existing markers first
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
gmarkers = [];
// add new markers from the JSON data
for (var i = 0, length = data.length; i < length; i++) {
latLng = new google.maps.LatLng(data[i].lat, data[i].lng);
bounds.extend(latLng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data[i].title
});
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description+"<br>"+marker.getPosition().toUrlValue(6));
infoWindow.open(map, marker);
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description+"<br>"+marker.getPosition().toUrlValue(6));
infoWindow.open(map, marker);
});
})(marker, data[i]);
gmarkers.push(marker);
}
// zoom the map to show all the markers, may not be desirable.
map.fitBounds(bounds);
};
function initialize() {
// initialize the map on page load.
var mapOptions = {
center: new google.maps.LatLng(35.66, -80.50),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
// add the markers to the map if they have been loaded already.
if (gmarkers.length > 0) {
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(map);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
https://developers.google.com/maps/documentation/javascript/reference
markerObject.setPosition(latlng:LatLng|LatLngLiteral)
I don't think you need to redraw the map, but in case you do:
google.maps.event.trigger(mapObject, 'resize');