Google map goes blank when triggering click event outside - google-maps

I have created a google map using V3 js API, and inside the map I am showing multiple markers. When I am clicking on a markers it does an ajax call and shows the result in the infowindow. I have added an external link outside the map, clicking on which it will display the corresponding marker result in side the map. I have used the below code to do the functionality..
$('#marker_link').click(function () {
var longitude = $(this).find("#longitude").val();
var latitude = $(this).find("#latitude").val();
var index = $(this).find("#index").val();
google.maps.event.trigger(gmarkers[index], "click", {
latLng: new google.maps.LatLng(latitude, longitude)
});
});
This code is pulling the marker data correctly and showing in a window. But at that time the map goes blank. How can we fix it. How can we keep the map along with the store result.
Here gmarkers[ ] is a global array where I am keeping all the markers that are created during the map is rendered.
The below code I have used while showing markers in the map for the first time.
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(pLat, pLong),
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function (event) {
var dataString = 'store_id=' + {{ store.store_id }}
$.ajax({
type: "GET",
url: GET_STORE_DATA,
data: dataString,
success: function(res) {
if(res != '') {
var contentString = res;
var infoWindow = new google.maps.InfoWindow({ content: contentString });
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
} else {
alert('No data found')
}
}
});
});

Related

Google Nearby change type on click

I'm working on a project where I'd like to show the choosen event on google maps with some additional information. (ex. all gas stations radius 2km).
Google doesn't allow a nearby search with multiple types.
Restricts the results to places matching the specified type. Only one type may be specified (if more than one type is provided, all types following the first entry are ignored).
So for now I'd like to change the type (ex. gas_station or store) if I click to a custom button I added.
(used the google document example)
Screenshot: http://imgur.com/qYwLuw4
Question:
Which is the best way to change the type and refresh the map with the new information?
I'd like to present you our solution.
We wrote a clear() and a showType() function, which will erase all markers and let the right ones appear on click. By the way we give the button a state class called "selected" for CSS styling.
We didn't find a solution to show both (washstation AND fuelstation).
<script type="text/javascript">
var map;
var infowindow;
var service;
var eventLocation = {lat: <?= $arrCoordinates['latitude']?>, lng: <?= $arrCoordinates['longitude']?>};
var markers = [];
var wash = document.getElementById('wash'); //washbutton
var fuel = document.getElementById('fuel'); //fuelstation button
function initMap() {
map = new google.maps.Map(document.getElementById('eventmap'), {
center: eventLocation,
zoom: 13,
});
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
showType('gas_station');
fuel.classList.add("selected");
typeControl(map);
}
// Type control function
function typeControl ( map ) {
google.maps.event.addDomListener(fuel, 'click', function() {
wash.classList.remove("selected");
fuel.classList.remove("selected");
clear()
showType('gas_station')
this.classList.add("selected");
});
google.maps.event.addDomListener(wash, 'click', function() {
wash.classList.remove("selected");
fuel.classList.remove("selected");
clear()
showType('car_wash')
this.classList.add("selected");
});
}
function showType(type) {
service.nearbySearch({
location: eventLocation,
radius: 10000,
type: [type]
}, callback);
}
function clear() {
markers.forEach(marker => marker.setMap(null));
markers = [];
}
function callback(results, status) {
clear()
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
createTuningEventMarker();
}
}
function createTuningEventMarker(place) {
var eventLocation = {lat: <?= $arrCoordinates['latitude']?>, lng: <?= $arrCoordinates['longitude']?>};
var eventIcon = {
url: 'https://www.foo.lol/img/icons/pin.svg',
// This marker is 20 pixels wide by 32 pixels high.
scaledSize: new google.maps.Size(60, 60),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(30,60)
};
var marker = new google.maps.Marker({
map: map,
icon:eventIcon,
position: eventLocation
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<?= $event['name']?>');
infowindow.open(map, this);
});
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name + "<br>Adress: " + place.vicinity);
infowindow.open(map, this);
});
}
</script>

Google Maps API - Activating the infowindow of a custom marker

I am trying to activate the infowindow for a custom marer, yielding a small description about the marker, I'm having some trouble at the moment, I have the custom marker working but I can't get the infowindow to show.
I tried calling the listener for the marker and storing it in a variable "customMarker", then calling another mouseover listener to activate the infowindow, but I'm having no luck, can anyone help me out?
var map;
//Creates a custom icon to be placed on the map
var goldStar = 'https://cdn2.iconfinder.com/data/icons/august/PNG/Star%20Gold.png';
function initialize() {
//Sets the zoom amount for the map, the higher the number, the closer the zoom amount
var mapOptions = {
zoom: 18
//center : myLatLng
};
//The map object itself
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var contentString = 'This is a custom toolTip';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
// Tries to find user location using HTML 5
if(navigator.geolocation)
{
//sets the map to the position of the user using location
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var customMarker = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng, map);
});
//This listener is not working
//google.maps.event.addListener(customMarker, 'mouseover', function() {
//infowindow.open(map,customMarker);
//});
}
function placeMarker(location, map)
{
var marker = new google.maps.Marker({
position: location,
icon: goldStar,
map: map,
title: "custom marker",
draggable:true
});
map.panTo(location);
}
The google.maps.event.addListener function does not return a marker. This won't work:
var customMarker = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng, map);
});
Assign the event listener in your placeMarker function to the marker you create (also gives the advantage of maintaining function closure on the marker):
function placeMarker(location, map) {
var marker = new google.maps.Marker({
position: location,
icon: goldStar,
map: map,
title: "custom marker",
draggable: true
});
var contentString = 'This is a custom toolTip';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,marker);
});
map.panTo(location);
}
working fiddle

Google maps v3 open infowindow on load

I using this technique: http://www.geocodezip.com/v3_MW_example_map2.html
I want to have the first info window open when the map loads.
I also want to be able to center the map when you click a location link.
Can anyone help?
JS:
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
var map = null;
function initialize() {
// create the map
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(50.822096, -0.375736),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel:false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Add markers to the map
// Set up three markers with info windows
// add the points
var point = new google.maps.LatLng(50.810438, -0.374925);
var center = new google.maps.LatLng(50.810438, -0.374925);
var marker = createMarker(point,"Worthing","<p><b>Worthing</b><br>1-13 Buckingham Road,<br>Worthing,<br>West Sussex,<br>BN11 1TH</p>")
var point = new google.maps.LatLng(51.497421,-0.141604);
var center = new google.maps.LatLng(51.497421,-0.141604);
var marker = createMarker(point,"London","<p><b>London</b><br>Portland House,<br>Bressenden Place,<br>London,<br>SW1E 5RS</p>")
var point = new google.maps.LatLng(-33.867487,151.20699);
var center = new google.maps.LatLng(-33.867487,151.20699);
var marker = createMarker(point,"Sydney","<p><b>Sydney</b><br>Level 1, Cosco House,<br>95-101 Sussex Street,<br>Sydney NSW<br>Australia 2000</p>")
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
$('#side_bar li:first-child').addClass("active");
$('#side_bar li').click(function(){
$('#side_bar li').removeClass("active");
$(this).addClass("active");
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var iconBase = '../Themes/FreshEgg/assets/img/';
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5,
icon: iconBase + 'map_marker_24x46.png',
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
infowindow.setContent(contentString);
infowindow.open(map,marker);
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<li><a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a></li>';
}
google.maps.event.addDomListener(window, 'load', initialize);
HTML:
<ul class="list-inline" id="side_bar"></ul>
<div id="map_canvas"></div>
Add a 4th parameter to your createMarker() function for the default state of markers - createMarker(latlng, name, html, show) - where show will be a boolean variable: true to open on load, false to leave it closed. Then when you call createMarker() in your initialize() method specify true for the marker you want open on load.
Then in createMarker() add a condition that handles this for you - something like:
if (show) {
google.maps.event.trigger(marker, "click");
/*if you're going to take this approach, make sure this is triggered after
*you specify your listener
*alternately, you can also setContent() and open() your infoWindow here
*/
}
To have the map pan to the center when you click on the marker, you first need to disable the auto panning of the map when an infoWindow is open. This can be done where you set the options for your infoWindow:
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50),
disableAutoPan : true
});
Then, in your listener for the click event on the marker add the function to panTo(LatLng) the position of the marker on your map.
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
map.panTo(marker.getPosition());
});

Can't load markers into Google Maps API from JSON

Thanks in advance for any help you can provide! I'm trying to create markers in my Google Map using JSON data. The good news is that I've got the data in the format I need it. The bad news is that I'm new to JSON, and I can't seem to get the markers to show up on the map. From the console's response, the issue seems to be the mapInit line at the bottom of the code below.
I have tried resolving this problem by reviewing solutions at different markers on google maps v3, Using JSON markers in Google Maps API with Javascript, and Google Maps API v3: Adding markers from an array doesn't work, among others. I've also tried duplicating the examples at http://weareallrobots.com/demos/map.html and other sites, but I'm still having trouble.
My code:
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var rendererOptions = {
draggable: true,
panel:document.getElementById('directions_panel')
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
// HERE'S WHERE PROBLEMS START
$.getJSON("mapall.js", {}, function(data){
$.each(data.masterlocation, function(i, item){
$("#markers").append('<li>' + item.nickname + '</li>');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.latitude, item.longitude),
map: map_canvas,
title: item.nickname
});
arrMarkers[i] = marker;
var infowindow = new google.maps.InfoWindow({
content: "<h3>"+ item.nickname +"</h3>"
});
arrInfoWindows[i] = infowindow;
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});
});
}
function calcRoute() {
UNRELATED ROUTING CODE HERE
}
// HERE'S WHERE MORE PROBLEMS START
$(function(){
// initialize map (create markers, infowindows and list)
mapInit();
// "live" bind click event
$("#markers a").live("click", function(){
var i = $(this).attr("rel");
// this next line closes all open infowindows before opening the selected one
//for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
arrInfoWindows[i].open(map, arrMarkers[i]);
});
});
</script>
My JSON Data
[{"masterlocation":{"latitude":"33.5","nickname":"First","longitude":"-86.8"}},{"masterlocation":{"latitude":"34.7","nickname":"Second","longitude":"-86.6"}},
UPDATE 1
As per comments from geocodezip and Adam, I've updated my code to the below. I added the + symbol before latitude and longitude, and I replaced mapInit with initialize. However, I'm still not getting any markers to show up. Firebug is telling me that I have errors in my jQuery file, but I'm not sure if these are related. Thanks for sticking with me!
Code:
// HERE'S WHERE PROBLEMS START
$.getJSON("mapall.js", {}, function(data){
$.each(data.masterlocation, function(i, item){
$("#markers").append('<li>' + item.nickname + '</li>');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(+item.latitude, +item.longitude),
map: map_canvas,
title: item.nickname
});
arrMarkers[i] = marker;
var infowindow = new google.maps.InfoWindow({
content: "<h3>"+ item.nickname +"</h3>"
});
arrInfoWindows[i] = infowindow;
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});
});
}
function calcRoute() {
UNRELATED ROUTING CODE HERE
}
// HERE'S WHERE MORE PROBLEMS START
$(function(){
// initialize map (create markers, infowindows and list)
initialize();
// "live" bind click event
$("#markers a").live("click", function(){
var i = $(this).attr("rel");
// this next line closes all open infowindows before opening the selected one
//for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
arrInfoWindows[i].open(map, arrMarkers[i]);
});
});
JQuery errors
TypeError: a is undefined
[Break On This Error]
...rn a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){...
jquery.js (line 29)
TypeError: a is undefined
[Break On This Error]
...rn a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){...
UPDATE 2
My current code is below, as well as the error codes I am getting in the console. New errors appeared when I reloaded the page, and they refer to the line in my javascript where function initialize first occurs. Maybe this is the problem?
Also, is it possible that the problem is in the JSON? Each JSON entry is preceded by the name of the MYSQL table, "Masterlocation" (see above.) In other JSON examples I've seen, the term that comes after the "." in "$.each(data.masterlocation)" only occurs once.
My Javascript:
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var rendererOptions = {
draggable: true,
panel:document.getElementById('directions_panel')
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
$.getJSON("mapall.js", {}, function(data){
console.log(data);
$.each(data.masterlocation, function(i, item){
console.log(item);
$("#markers").append('<li>' + item.nickname + '</li>');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(+item.latitude, +item.longitude),
map: map,
title: item.nickname
});
arrMarkers[i] = marker;
var infowindow = new google.maps.InfoWindow({
content: "<h3>"+ item.nickname +"</h3>"
});
arrInfoWindows[i] = infowindow;
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});
});
}
function calcRoute() {
ROUTING CODE
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: optimize,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
}
$(function(){
// initialize map (create markers, infowindows and list)
initialize();
// "live" bind click event
$("#markers a").live("click", function(){
var i = $(this).attr("rel");
// this next line closes all open infowindows before opening the selected one
//for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
arrInfoWindows[i].open(map, arrMarkers[i]);
});
});
</script>
Javascript Errors from Console: these only occurred after I reloaded the page.
Uncaught TypeError: Cannot read property 'length' of undefined jquery.js:29
c.extend.each jquery.js:29
(anonymous function) mapall:87
b jquery.js:121
w.onreadystatechange jquery.js:127
Uncaught TypeError: Cannot read property 'length' of undefined jquery.js:29
c.extend.each jquery.js:29
(anonymous function) mapall:87
b jquery.js:121
w.onreadystatechange jquery.js:127
In addition to any other errors, the way you're accessing the JSON data doesn't match the format of that data.
Your code to access the JSON data is:
$.getJSON( "mapall.js", {}, function( data ) {
$.each( data.masterlocation, function( i, item ) {
... use item.nickname, item.latitude, and item.longitude here
});
});
Now there's nothing wrong with that code, if the JSON data looked like this:
{
"masterlocation": [
{
"nickname": "First",
"latitude": 33.5,
"longitude": -86.8
},
{
"nickname": "Second",
"latitude": 34.7,
"longitude": -86.6
}
]
}
This JSON data is an object with a single property named masterlocation. That property is an array of objects, each one containing nickname, a string, and latitude and longitude, two numbers.
That's a pretty sensible way to lay out the JSON data. I would do it just about the same myself. (The only things I can think of changing would be the naming conventions: I'd probably use a name like locations instead of masterlocation because I like to see plural names for arrays, and I like shorter names for commonly-used properties, e.g. name, lat, and lng. But that's purely a matter of style—the structure I'd use is identical aside for names.)
Unfortunately, your actual JSON data looks like this:
[
{
"masterlocation": {
"latitude": "33.5",
"nickname": "First",
"longitude": "-86.8"
}
},
{
"masterlocation": {
"latitude": "34.7",
"nickname": "Second",
"longitude": "-86.6"
}
}
]
This is an array of two elements. Each element is an object with one property named masterlocation. Each masterlocation object contains the nickname, latitude, and longitude properties. And the latitude and longitude are strings instead of numbers like they should be.
It would be easy enough to change your code to work with this structure:
$.getJSON( "mapall.js", {}, function( data ) {
$.each( data, function( i, item ) {
var loc = item.masterlocation;
... use loc.nickname, +loc.latitude, and +loc.longitude here
});
});
But if you have the option of changing the format of your JSON format, I'd do that instead. You had the right idea in your JavaScript code, just change the JSON output to match.
Make sure the latitude and longitude are actually numbers in JS, not strings.
To do a type convert, just put a + in front of the string
position: new google.maps.LatLng(+item.latitude, +item.longitude)
For some reason, google's API was not built smart enough to handle passing in strings containing numbers....go figure.
EDIT
Ditto to the comment on your post as well - you are calling a function mapInit() but you should be calling the function initialize() from the looks of it.
EDIT2
This line:
map: map_canvas,
should be
map: map,

Google maps infowindow

I am trying to create listeners for some map markers. I can create the markers and they are on the map but, no matter which marker I click on it tells me "Uncaught TypeError: Cannot call method 'open' of undefined" . When I break at the open code it is showing markers[46] which is one more that the highest index. And it doesnt matter which marker I click on its always the same index.
EDIT: I edited the code and pasted all of it. No errors, but nothing happens when I click a marker. I am looking in Chrome and it looks like there isnt a event handler registered
<script>
var map;
var nav = [];
$(document).ready(function () {
//initialise a map
init();
var infowindow = new google.maps.InfoWindow({});
$.get("xxxxxx.kml", function (data) {
html = "";
//loop through placemarks tags
i = 1;
$(data).find("Placemark").each(function (index, value) {
//get coordinates and place name
coords = $(this).find("coordinates").text();
contentString = $(this).find("description").text();
var partsOfStr = coords.split(',');
var lat = parseFloat(partsOfStr[0]);
var lng = parseFloat(partsOfStr[1]);
var myLatLng = new google.maps.LatLng(lng, lat);
place = $(this).find("name").text();
createMarker(myLatLng, place, contentString, i)
//store as JSON
c = coords.split(",")
nav.push({
"place": place,
"lat": c[0],
"lng": c[1]
})
//output as a navigation
html += "<li>" + place + "</li>";
i++;
});
//output as a navigation
$(".navigation").append(html);
//bind clicks on your navigation to scroll to a placemark
$(".navigation li").bind("click", function () {
panToPoint = new google.maps.LatLng(nav[$(this).index()].lng, nav[$(this).index()].lat)
map.panTo(panToPoint);
})
});
markers = [];
function createMarker(myLatLng, title, contentString, i) {
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: title
});
google.maps.event.addListener(markers, 'click', function () {
infoWindow.setContent(contentString);
infowindow.open(map, markers[i]);
});
markers[i] = marker;
return marker
}
function init() {
//google.maps.event.addDomListener(window, 'init', Initialize);
var latlng = new google.maps.LatLng(39.047050, -77.131409);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
})
This is almost a FAQ. When your loop ends, the value of i is 46 (based on your statement). There is no marker 46, so all the click listeners fail. It can be solved with function closure (a createMarker function which holds the association between the marker and the infowindow contents).
Something like this in your example (not tested), call it from inside your marker creation loop, requires a global markers array, but doesn't require the global infowindow array:
//global markers array
markers = [];
// global infowindow
var infowindow = new google.maps.InfoWindow({});
// createMarker function
function createMarker(myLatLng, title, contentString, i)
{
var marker = new google.maps.Marker({
position: myLatlng ,
map: map,
title:title
});
google.maps.event.addListener(markers, 'click', function() {
infoWindow.setContent(contentString);
infowindow.open(map,markers[i]);
});
markers[i] = marker;
return marker
}