JQuery:Google map loads partially - javascript

I am trying to integrate GoogleMap in hash page in my project.When I navigate from a page to mappage
googlemap loads partially.When i refresh this hash page it loads successfully.This is the code :
function markicons() {
InitializeMap();
var ltlng = [];
ltlng.push(new google.maps.LatLng(-36.847043, 174.761543));
ltlng.push(new google.maps.LatLng(-37.791174,175.297813));
ltlng.push(new google.maps.LatLng(-38.679988,176.077843));
ltlng.push(new google.maps.LatLng(-41.297257,174.759483));
map.setCenter(ltlng[0]);
for (var i = 0; i <= ltlng.length; i++) {
marker = new google.maps.Marker({
map: map,
position: ltlng[i]
});
(function (i, marker) {
google.maps.event.addListener(marker, 'click', function () {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent("Message" + i);
infowindow.open(map, marker);
});
})(i, marker);
}
}
window.onload = markicons;
How can I fix this problem?Please suggest a solution.

I got the solution.I just called markicons() inside the window.hashchange function not in the window.load.Here is the code:
$(window).on("hashchange", function () {
if(window.location.hash=="#contactUI")
{
markicons();
}
});

Related

Marker Google Maps Show/Hide OnClick

I am trying to make google maps project, I was showing my marker on my map.
But now I want to make show/hide marker when I click checkbox,
this my code for showing marker in my maps, data for my marker I get from MySQL,
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: (lat,long)
});
var infowindow = new google.maps.InfoWindow({});
var latArea = new Array();
var longArea = new Array();
for (i = 0; i < $$; i++) //looping until all data from mysql
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(latArea[i], longArea[i]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('<b>Coordinat : </b>'+String(latArea[i])+' , '+
String(longArea[i]));
infowindow.open(map, marker);
}
})(marker, i));
}
}
I was successfully displaying all data to marker in maps and add function for hide/show marker but only one marker is hide/show not all,
this my code for show/hide function
function toggleMarker() {
if (!marker.getVisible()) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
Thank you.
i was solving this problem,
this is correct code,
<script>
var markers = new Array();
function initialize() {
var latArea = new Array();
var longArea = new Array();
var i, newMarker;
for (i = 0; i < $$; i++)
{
newMarker = new google.maps.Marker({
position: new google.maps.LatLng(latArea[i], longArea[i]),
map: map,
icon: icon,
newMarker.category = 'show';
newMarker.setVisible(false);
markers.push(newMarker);
}
}
function displayMarkers(obj,category) {
var i;
for (i = 0; i < $$; i++)
{
if (markers[i].category === category) {
if ($(obj).is(":checked")) {
markers[i].setVisible(true);
} else {
markers[i].setVisible(false);
}
} else {
markers[i].setVisible(false);
}
}
}
and this checkbox in html for show/hidden marker
<input type="checkbox" onclick="displayMarkers(this,'area');" />

infowindow is not updating with marker google maps

I am developing a web page for viewing vehicle locations using gps data.
I have make the back end working fine with the help of Mr. Aruna a genius in stack Overflow. Now I need a help for updating my google map infowindow. marker is updating its location no issue with that. while clicking it is not updating is current speed and another info according to that.
Below is the code in
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
getMarkers();
function getMarkers() {
var infowindow = null;
$.get('/markers', {}, function (res, resp) {
console.dir(res);
for (var i = 0, len = res.length; i < len; i++) {
var content = res[i].name + " S1: " + res[i].speed * 1.6 + '<br />' + "D: " + res[i].lastupdate
infowindow = new google.maps.InfoWindow({
content: "A"
});
//Do we have this marker already?
if (markerStore.hasOwnProperty(res[i].id)) {
console.log('just move it...');
markerStore[res[i].id].setPosition(new google.maps.LatLng(res[i].position.lat, res[i].position.long));
//markerStore[res[i].id].setMap(map);
// Not sure below block and its not updating
google.maps.event.addListener(markerStore[res[i].id], 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, markerStore[res[i].id]);
};
})(markerStore[res[i].id], content, infowindow));
} else {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(res[i].position.lat, res[i].position.long),
title: res[i].name,
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, marker);
};
})(marker, content, infowindow));
//var marker = new google.maps.Marker({
// position: new google.maps.LatLng(res[i].position.lat, res[i].position.long),
// title: res[i].name,
// map: map
//});
//google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
// return function () {
// infowindow.setContent(content);
// infowindow.open(map, marker);
// };
//})(marker, content, infowindow));
markerStore[res[i].id] = marker;
console.log(marker.getTitle());
}
}
window.setTimeout(getMarkers, INTERVAL);
}, "json");
}
Please help me ...
Your click event listener is called asynchronously, long after your for loop has completed. So the value of i is not what you expect.
This is easy to fix (assuming there are not other problems as well).
Take all of the code inside the for loop body and make it a function. I'll call the function addMarker( item ), but of course you can use any name you want.
Everywhere you have res[i] in that function, change it to item. Then shorten the for loop so it contains only a single line: addMarker( res[i] );.
So now your code looks like this:
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
getMarkers();
function getMarkers() {
var infowindow = null;
$.get('/markers', {}, function (res, resp) {
console.dir(res);
for (var i = 0, len = res.length; i < len; i++) {
addMarker( res[i] );
}
function addMarker( item ) {
var content = item.name + " S1: " + item.speed * 1.6 + '<br />' + "D: " + item.lastupdate
infowindow = new google.maps.InfoWindow({
content: "A"
});
//Do we have this marker already?
if (markerStore.hasOwnProperty(item.id)) {
console.log('just move it...');
markerStore[item.id].setPosition(new google.maps.LatLng(item.position.lat, item.position.long));
//markerStore[item.id].setMap(map);
// Not sure below block and its not updating
google.maps.event.addListener(markerStore[item.id], 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, markerStore[item.id]);
};
})(markerStore[item.id], content, infowindow));
} else {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.position.lat, item.position.long),
title: item.name,
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, marker);
};
})(marker, content, infowindow));
//var marker = new google.maps.Marker({
// position: new google.maps.LatLng(item.position.lat, item.position.long),
// title: item.name,
// map: map
//});
//google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
// return function () {
// infowindow.setContent(content);
// infowindow.open(map, marker);
// };
//})(marker, content, infowindow));
markerStore[item.id] = marker;
console.log(marker.getTitle());
}
}
window.setTimeout(getMarkers, INTERVAL);
}, "json");
}
I didn't check for any other errors in your code, but this will fix the specific problem you are asking about.
To learn more about this, read up on JavaScript closures.

JavaScript multidimensional array cannot access as array, only as string

I am trying to put multiple markers on a Google map. I have JS that builds an array and passes it to the Google function that handles markers.
Problem is, when I try to access the supposed array, I just get the first character as if it's a string.
$(document).ready(function () {
// initialize map to center on florida.
initializeGMap();
var locations = [];
#foreach (var item in Model)
{
<text>
locations.push(#Html.Raw(Json.Encode("'" + item.Name + "'," + item.Location.Latitude + "," + item.Location.Longitude + "")));
</text>
}
addMarker(locations);
});
I've tried several (read: 20+) variations of this including JSON.stringify it before sending, after sending, etc. Here's the function it gets passed too:
function addMarker(locations) {
var locations = JSON.stringify(locations);
alert(locations + '\n' + locations[0][0] + '\n' + locations[0][1]);
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));
}
alert("done");
}
When it gets to the line with 'locations[x][x]' all I ever get back in '[' which is the first character of the JSON string. It's not being treated at an array.
What am I missing?
I solved it via:
$(document).ready(function () {
// initialize map to center on florida.
initializeGMap();
// serialize model locations
var locationsToPass = #Html.Raw(Json.Encode(Model.Select(x => new { x.Name, x.Location.Latitude, x.Location.Longitude })));
addMarker(locationsToPass);
});
and in the receiving function:
function addMarker(locations) {
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].Latitude, locations[i].Longitude),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i].Name);
infowindow.open(map, marker);
}
})(marker, i));
}
}
The key to troubleshooting was using this to detect if I was passing an array or not:
variable.constructor === Array
which I got here.

Recalculate markercluster onclick of filter

JS FIDDLE HERE:
http://jsfiddle.net/useyourillusiontoo/g77np63c/1/
I've created a google map that plants markers down and allows my to filter then with checkboxes without the page or map reloading. Yay!
Next I added marker cluster which worked too. However, when I now click on my markers the cluster doesn't update. That is.. the number inside the cluster doesnt change to reflect markers that are being hidden/displayed.
When I zoom in the markers are still being hidden/displayed but its just the cluster doesn't show this when zoomed out.
I've pasted my code below and would love any advice because i've been scratching my head.
var map;
var infowindow;
var image = [];
var gmarkers = [];
var clusterMarkers = [];
function mapInit(){
var centerCoord = new google.maps.LatLng(53.01265600000,-1.466105200000);
var mapOptions = {
zoom: 6,
center: centerCoord,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
addLocation();
var markerCluster = new MarkerClusterer(map, clusterMarkers);
function addLocation(place,category) {
for (var x in points){
var development = points[x];
var location = new google.maps.LatLng(development.lat, development.lng);
storeMarker(location, development);
}
}
function storeMarker(location, development){
var latLng = location;
var storedmarker = new google.maps.Marker({
position: latLng
});
storedmarker.mycategory = development.tid;
google.maps.event.addListener(storedmarker, 'click', function() {
if(typeof infowindow != 'undefined') infowindow.close();
infowindow = new google.maps.InfoWindow({
content: "<h3>"+ development.name +"</h3><a href='http://www.bbc.co.uk'>Show more!</a>"
});
infowindow.open(map, storedmarker);
});
clusterMarkers.push(storedmarker);
}
function show(category) {
for (var i=0; i<clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
clusterMarkers[i].setVisible(true);
}
}
document.getElementById(category+"box").checked = true;
}
function hide(category) {
for (var i=0; i<clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
clusterMarkers[i].setVisible(false);
}
}
document.getElementById(category+"box").checked = false;
infowindow.close();
}
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
}
jQuery(document).ready(function($) {
$('.b2bfilter').click(function () {
boxclick(this, this.value);
});
});
}
jQuery(document).ready(function(){
mapInit();
});
added markers as requested. They are a basic JSON object
var points = [
{"name":"House","lat":"53.341265600000","lng":"- 1.466105200000","tid":"1"},
{"name":"Old house","lat":"53.361066200000","lng":"-1.465752700000","tid":"2"}]
setting the visible-property will not have an effect when a marker is inside a cluster, you must also remove/add the marker from/to the markerclusterer.
Possible solution:
observe the visible_changed -event of the markers:
google.maps.event.addListener(storedmarker,'visible_changed',function(){
markerCluster[(this.getVisible())?'addMarker':'removeMarker'](this)
});
http://jsfiddle.net/doktormolle/g77np63c/4/
another(possibly better) approach(especially whene there are a lot of markers, because the solution above will force a redraw of the clusters for each affected marker):
First collect all affected markers and then use addMarkers/showMarkers to toggle them:
function toggle(category, show) {
var markers = [];
for (var i = 0; i < clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
markers.push(clusterMarkers[i]);
clusterMarkers[i].setVisible(show);
}
}
if (markers.length) {
markerCluster[(show) ? 'addMarkers' : 'removeMarkers'](markers);
}
if (!show && infowindow) infowindow.close();
}
function boxclick(box, category) {
toggle(category, box.checked);
}
jQuery(document).ready(function ($) {
$('.b2bfilter').click(function () {
boxclick(this, this.value);
});
});
http://jsfiddle.net/doktormolle/g77np63c/5/

Dynamically populated google maps sidebar

I've been using the code from this V3 example to set up a links bar that dynamically populates when different category filters are selected, but have two problems at the moment. Firstly, I've put the the initial makeSidebar function in the map's idle event, but the sidebar is only created when the map is moved, not on loading of the page. Secondly, I can't seem to get the marker infowindow to open when the corresponding link is clicked in the sidebar. My code is below:
var map;
var infowindow;
var image = [];
var gmarkers = [];
var place;
var side_bar_html = "";
image['attraction'] = 'http://google-maps-icons.googlecode.com/files/beach.png';
image['food'] = 'http://google-maps-icons.googlecode.com/files/restaurant.png';
image['hotel'] = 'http://google-maps-icons.googlecode.com/files/hotel.png';
image['city'] = 'http://google-maps-icons.googlecode.com/files/smallcity.png';
function mapInit(){
var placeLat = jQuery("#placelat").val();
var placeLng = jQuery("#placelng").val();
var centerCoord = new google.maps.LatLng(placeLat, placeLng);
var mapOptions = {
zoom: 15,
center: centerCoord,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListener(map, 'idle', function() {
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var yMaxLat = ne.lat();
var xMaxLng = ne.lng();
var yMinLat = sw.lat();
var xMinLng = sw.lng();
//alert("bounds changed");
updateMap(yMaxLat, xMaxLng, yMinLat, xMinLng);
show("attraction");
show("food");
show("hotel");
show("city");
makeSidebar();
});
function updateMap(yMaxLat, xMaxLng, yMinLat, xMinLng) {
jQuery.getJSON("/places", { "yMaxLat": yMaxLat, "xMaxLng": xMaxLng, "yMinLat": yMinLat, "xMinLng": xMinLng }, function(json) {
if (json.length > 0) {
for (i=0; i<json.length; i++) {
var place = json[i];
var category = json[i].tag;
var name = json[i].name;
addLocation(place,category,name);
//makeSidebar();
}
}
});
}
function addLocation(place,category,name) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(place.geom.y, place.geom.x),
map: map,
title: place.name,
icon: image[place.tag]
});
//var iwNode = document.getElementById("infowindow");
marker.mycategory = category;
marker.myname = name;
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({
content: "<div id='infowindow'><div id='infowindow_name'><p>"+ place.name +"</p></div><div id='infowindow_contents'><p>" + place.tag +"</p><a href='/places/"+place.id+"' id='place_link'>Show more!</a></div></div>"
});
infowindow.open(map, marker);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
});
}
function show(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(true);
}
}
document.getElementById(category+"box").checked = true;
}
function hide(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(false);
}
}
document.getElementById(category+"box").checked = false;
infowindow.close();
}
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
makeSidebar();
}
jQuery('#attractionbox').click(function() {
boxclick(this, 'attraction');
});
jQuery('#foodbox').click(function() {
boxclick(this, 'food');
});
jQuery('#hotelbox').click(function() {
boxclick(this, 'hotel');
});
jQuery('#citybox').click(function() {
boxclick(this, 'city');
});
function myclick(i) {
google.maps.event.trigger(gmarkers[i],"click");
}
function makeSidebar() {
//var html = "";
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
side_bar_html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>';
}
}
document.getElementById("side_bar").innerHTML = side_bar_html;
}
}
jQuery(document).ready(function(){
mapInit();
//makeSidebar();
});
Any help would be much appreciated - what can I do to get the sidebar loaded when the page loads, and to get the link click event working? Thanks!
The reason your links are not working is that you are defining your my_click and makeSidebar functions inside of your mapInit function and so they are not available outside of the scope of mapInit. Simply move them outside of mapInit and everything should just work.
As for the load event ... what you are looking for is the addDomListener method of google.maps.event. Simply use
google.maps.event.addDomListener(window, 'load', name_of_your_inital_function);
// e. g. google.maps.event.addDomListener(window, 'load', mapInit);
Finally; notta bene ... don't do this:
var image = [];
image['attraction'] = 'data';
image['food'] = 'more data';
Arrays are not meant to be used as hashes in Javascript. Use objects for dictionaries / hashes instead -- it's what you are actually doing (Array "subclasses" Object) and it will make it easier for others to use your code (and save you from headaches down the line).
var image = {};
image['attraction'] = 'data';
image['food'] = 'more data';

Categories