google map api V3 javascript markers on click display - google-maps

Some troubles with the following code.
Works perfectly but I would display the assiociate legend in KML files to the makers when "click" on it...
I would like a general command, cause markers can be more than 500...
Any help ?
the URL : http://tequila357.wix.com/test-projet#!map/c161y
Thanks
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
// lets define some vars to make things easier later
var kml = {
a: {
name: "MAP BELGIUM",
url: "https://maps.google.be/maps/ms?authuser=0&vps=2&hl=fr&ie=UTF8&msa=0&output=kml&msid=208899208399411894595.0004d24e3bd5bbd990f5d"
},
b: {
name: "GARDIENNES",
url: "https://maps.google.be/maps/ms?authuser=0&vps=3&hl=fr&ie=UTF8&msa=0&output=kml&msid=208899208399411894595.0004d21a429f0f00d5400"
},
c: {
name: "CRECHES",
url: "https://maps.google.be/maps/ms?authuser=0&vps=2&hl=fr&ie=UTF8&msa=0&output=kml&msid=208899208399411894595.0004d22900ca6b246c6a1"
},
d: {
name: "CRECHES PRIV",
url: "https://maps.google.be/maps/ms?authuser=0&vps=2&hl=fr&ie=UTF8&msa=0&output=kml&msid=208899208399411894595.0004d24cf21e2a254a10c"
},
e: {
name: "MAGASINS STORES",
url: "https://maps.google.be/maps/ms?authuser=0&vps=2&hl=fr&ie=UTF8&msa=0&output=kml&msid=208899208399411894595.0004d24db929a46bae78c"
},
f: {
name: "BABYSITTERS",
url: "https://maps.google.be/maps/ms?authuser=0&vps=2&hl=fr&ie=UTF8&msa=0&output=kml&msid=208899208399411894595.0004d24dba905263481df"
},
// keep adding more if ye like
};
// initialize our goo
function initializeMap() {
var options = {
center: new google.maps.LatLng(50.5812, 4.5687),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), options);
createTogglers();
};
google.maps.event.addDomListener(window, 'load', initializeMap);
// the important function... kml[id].xxxxx refers back to the top
function toggleKML(checked, id) {
if (checked) {
var layer = new google.maps.KmlLayer(kml[id].url, {
preserveViewport: true,
suppressInfoWindows: true
});
// store kml as obj
kml[id].obj = layer;
kml[id].obj.setMap(map);
}
else {
kml[id].obj.setMap(null);
delete kml[id].obj;
}
};
// create the controls dynamically because it's easier, really
function createTogglers() {
var html = "<form><ul>";
for (var prop in kml) {
html += "<li id=\"selector-" + prop + "\"><input type='checkbox' id='" + prop + "'" +
" onclick='highlight(this,\"selector-" + prop + "\"); toggleKML(this.checked, this.id)' \/>" +
kml[prop].name + "<\/li>";
}
html += "<li class='control'><a href='#' onclick='removeAll();return false;'>" +
"Remove all layers<\/a><\/li>" +
"<\/ul><\/form>";
document.getElementById("toggle_box").innerHTML = html;
};
// easy way to remove all objects
function removeAll() {
for (var prop in kml) {
if (kml[prop].obj) {
kml[prop].obj.setMap(null);
delete kml[prop].obj;
}
}
};
// Append Class on Select
function highlight(box, listitem) {
var selected = 'selected';
var normal = 'normal';
document.getElementById(listitem).className = (box.checked ? selected: normal);
};
function startup() {
// for example, this toggles kml b on load and updates the menu selector
var checkit = document.getElementById('a');
checkit.checked = true;
toggleKML(checkit, 'a');
highlight(checkit, 'selector1');
}
// test legen
google.maps.event.addListener(map, 'click', function(event) {
marker = new google.maps.Marker({position: event.latLng, map: map});
});
// end legend
</script>
<style type="text/css">
.selected { font-weight: bold; }
</style>
</head>
<body onload="startup()">
<div id="map_canvas" style="width: 100%; height: 700px;"></div>
<div id="toggle_box" style="position: absolute; top: 100px; right: 20px; padding: 10px; background: #fff; z-index: 5; "></div>
</body>
</html>

If you are looking for a "sidebar", that is not currently possible with KmlLayer.
You have at least two options:
import the KML into FusionTables, use FusionTablesLayer to display the markers/polygon on the map, query the table in an onclick handler for the sidebar to open the InfoWindow.
example
Use a third party KML parser like geoxml3 or geoxml-v3
example using geoxml3
To enable the InfoWindow to appear on click, remove this from the the code that initializes the KmlLayer:
suppressInfoWindows: true

Related

Google Maps MarkerClusterer not showing any default images

I'm adding javascript code snippet to my Wordpress post (Hosted by a 3rd Party). I managed to create an array of Markers, and had them added to the MarkerClusterer and Map. The cluster shows up but as a broken image link and a number.
How do I access the MarkerClusterer default images? I followed the instructions from https://github.com/googlemaps/js-markerclusterer/blob/main/README.md
I'm not sure how to use npm with the 3rd party hosting. I don't use a database with my website. I'm calling src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js" to import MarkerClusterer
<div id="gmap" style="width:100%;height:400px;"></div>
<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"</script>
var mymap;
var markers = [];
function initMap() {
var centerpoint = { lat: 38.5, lng: -98 }; //centered around Kansas
mymap = new google.maps.Map(document.getElementById('gmap'), {
zoom: 4,
center: centerpoint
});
}
/** fetching a cvs file on the server side with a list of locations */
fetch("https://mywebsite.com/wp-content/uploads/2022/03/stores.csv")
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.text().then(function(data) {
count = 0;
console.log("fetch called successfully");
initMap();
processCSV(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
function processCSV(allData){
const rows = allData.split('\n');
var storename, storephone, storeaddress, storelat, storelng;
for(let i=0; i<rows.length; i++){
var line = rows[i];
storename = line.split(",")[1];
storephone = line.split(",")[3];
storeaddress = String(line.split(",")[2]);
storeaddress = replaceAll(storeaddress, "^", ",");
storelat = line.split(",")[4];
storelng = line.split(",")[5];
createMarker(storename, storephone, storeaddress, storelat, storelng);
}
createCluster();
}
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
function createCluster(){
var mcluster =new MarkerClusterer( mymap , markers);
}
function createMarker(name, phone, address, latstr, lngstr) {
var contentString = "<b>" + name + "</b><br><br><i>" + phone + "</i><br><br>" + address;
var latLng = { lat: Number(latstr) , lng: Number(lngstr)};
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: mymap,
title: name
});
markers.push(marker);
console.log("added marker to map" + name);
marker.addListener("click", () => {
infowindow.open({
anchor: marker,
map: mymap,
shouldFocus: false,
});
});
}
<script src="https://maps.googleapis.com/maps/api/js?key=<PRIVATEKEY>;callback=initMap"></script>
The version of MarkerClusterer you are using doesn't require ClusterIcons (unless you want to change them), they default to SVG icons coded inline.
When I run the posted code I get a javascript error: Uncaught (in promise) ReferenceError: MarkerClusterer is not defined.
That is because according to the documentation when you include the library the way you are (<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"></script>), the constructor for the MarkerClusterer is accessed as:
When adding via unpkg, the MarkerClusterer can be accessed at markerClusterer.MarkerClusterer.
Changing that, makes the clusters appear.
proof of concept fiddle
code snippet:
var mymap;
var markers = [];
function initMap() {
var centerpoint = {
lat: 40.7127753,
lng: -74.0059728
}; //centered around New York City
mymap = new google.maps.Map(document.getElementById('gmap'), {
zoom: 4,
center: centerpoint
});
processCSV(data);
}
var data = '"","New York","New York^ NY","516-555-5555",40.7127753, -74.0059728\n"","Newark","Newark^ NJ","201-555-5555",40.735657, -74.1723667';
function processCSV(allData) {
console.log(allData);
const rows = allData.split('\n');
var storename, storephone, storeaddress, storelat, storelng;
for (let i = 0; i < rows.length; i++) {
var line = rows[i];
storename = line.split(",")[1];
storephone = line.split(",")[3];
storeaddress = String(line.split(",")[2]);
storeaddress = replaceAll(storeaddress, "^", ",");
storelat = line.split(",")[4];
storelng = line.split(",")[5];
createMarker(storename, storephone, storeaddress, storelat, storelng);
}
createCluster();
}
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
function createCluster() {
var mcluster = new markerClusterer.MarkerClusterer({
map: mymap,
markers: markers
});
}
function createMarker(name, phone, address, latstr, lngstr) {
var contentString = "<b>" + name + "</b><br><br><i>" + phone + "</i><br><br>" + address;
var latLng = {
lat: Number(latstr),
lng: Number(lngstr)
};
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: mymap,
title: name
});
markers.push(marker);
console.log("added marker to map" + name);
marker.addListener("click", () => {
infowindow.open({
anchor: marker,
map: mymap,
shouldFocus: false,
});
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#gmap {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="gmap"></div>
<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"></script>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>
</html>

Using event listeners for Google Maps overlays instead of markers?

Below I have a snippet which generates a marker and a mapLabel (which extends the overlay class) on a google map.
I have tried to implement an event listener which deletes the overlay by right clicking, the same way I do with the marker, but it does not work!!!
I am not sure how to make it work, I have tried using "DomListener" and various iterations, but it doesn't even seem to hit that line of code when I debug.
How do I make it so that I can right click to delete my mapLabel object???
var map;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13
});
addPlace();
placeLabel();
}
function addPlace() {
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(37.4419, -122.1419)
});
google.maps.event.addListener(marker, 'rightclick', function() {
this.setMap(null);
});
}
function placeLabel() {
var mapLabel = new MapLabel({
text: 'Right click to delete??',
position: new google.maps.LatLng(37.4419, -122.1419),
map: map,
fontSize: 21,
align: 'center'
});
google.maps.event.addListener(mapLabel, 'rightclick', function() {
this.setMap(null);
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 250px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://googlemaps.github.io/js-map-label/src/maplabel-compiled.js"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>
MapLabel doesn't have event listeners, but MarkerWithLabel does. The way it's done there is they have a almost-transparent div laying over the label. Any listeners are added to this div.
Something similar can be done with the MapLabel. Have a look at the source code of MarkerWithLabel here: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/src/markerwithlabel.js
Here are a few code snippets from my own MapLabel alternative. It's not complete and untested, but it should get you started.
MapLabel.prototype.onAdd = function() {
var eventDiv = this.eventDiv_ = document.createElement('div');
// ...
this.drawCanvas_();
this.drawEventDiv_();
var panes = this.getPanes();
if (panes) {
panes.overlayMouseTarget.appendChild(eventDiv);
panes.overlayImage.appendChild(canvas);
}
// ...
};
Add the div to overlayMouseTarget, the uppermost layer.
MapLabel.prototype.drawEventDiv_ = function() {
var eventDiv = this.eventDiv_;
if (!eventDiv) return;
var canvasWidth = this.canvas_.getContext('2d').measureText(this.get('text')).width;
var canvasHeight = this.get('fontSize');
eventDiv.innerHTML = this.get('text');
// This is needed for proper behavior on MSIE:
eventDiv.setAttribute("onselectstart", "return false;");
eventDiv.setAttribute("ondragstart", "return false;");
var eventDivStyle = this.eventDiv_.style;
eventDivStyle.width = canvasWidth + 'px';
eventDivStyle.height = canvasHeight + 'px';
eventDivStyle.cssText = this.get('text');
eventDivStyle.font = this.get('fontSize') + 'px ' + this.get('fontFamily');
eventDivStyle.position = 'absolute';
eventDivStyle.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE
eventDivStyle.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\"";
eventDivStyle.filter = "alpha(opacity=1)"; // For MSIE
eventDivStyle.marginLeft = this.getMarginLeft_(canvasWidth) + 'px';
eventDivStyle.zIndex = /** #type number */(this.get('zIndex'));
};
To add an event listener do this:
google.maps.event.addDomListener(this.eventDiv_, 'click', function (e) {
//..
this_.cAbortEvent(e); // Prevent click from being passed on to map
});
cAbortEvent prevents bubbling.
MapLabel.prototype.cAbortEvent = function(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
Try using 'mousedown' instead of 'rightclick', then distinguish which type of click it was.
google.maps.event.addListener(mapLabel, 'mousedown', function(e) {
if(e.which === 3)
{
this.setMap(null);
}
});
Mouse Click Codes MSDN API:
0: No button
1: Left button
2: Middle button (if present)
3: Right button

Printing page with multiple embedded Google Maps in WebKit produces tile errors

Printing the following example page in either Chrome or Safari on Mac (i.e., WebKit) produces misplaced map tiles in the printed output from the second map onwards. It works on the webpage itself, and printing it does also seem to work in Firefox. Need it to work in Chrome or Safari, though.
Example page: http://matsch.binaervarianz.de/tmp/print_entries.html
Print-to-PDF output of the page: http://matsch.binaervarianz.de/tmp/print_entries.pdf
(See, e.g., the displacement of road US421 on page 2 onwards.)
It looks like a caching problem that only affects printing. But clearing the cache or private/incognito browsing doesn't solve the issue.
While in the example all map sections are the same are, the problem also occurs with different maps (e.g., try panning and zooming in the example).
I'm OK with a partial solution where I can get it to work in my own browser -- i.e., it does not have to work for everyone, but it must be Webkit (Safari or Chrome). Can't use Firefox for this...
Bonus points if this works for everyone.
Here is some code how maps are initialized. More in the example page above.
// first map
var snippets = [];
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510463",
snippet_location_long: "-86.2288448"
});
var mapData_2899_1 = {
snippets: snippets,
entry_approx_location_lat: "",
entry_approx_location_long: ""
};
showMap(mapData_2899_1, "2899_1");
// second map
snippets = [];
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510639",
snippet_location_long: "-86.2287998"
});
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510739",
snippet_location_long: "-86.2288998"
});
var mapData_2899_3 = {
snippets: snippets,
entry_approx_location_lat: "",
entry_approx_location_long: ""
};
showMap(mapData_2899_3, "2899_3");
// show map function
function showMap(d, primKey) {
$( '#map-' + primKey ).addClass('map-canvas');
var mapOptions = {
center: { lat: 39.9513164, lng: -86.2274201 },
streetViewControl: false, zoom: 12,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('map-' + primKey), mapOptions);
$.each(d.snippets, function( i, snippet ) {
// location when snippet was recorded
if (snippet.snippet_location_lat !== "" && snippet.snippet_location_long !== "") {
var snippetLoc = new google.maps.LatLng(
p(snippet.snippet_location_lat),
p(snippet.snippet_location_long)
);
var marker = new google.maps.Marker({ position: snippetLoc, map: map });
}
// approximate location taking into account how long ago the event reportadly took place
if (snippet.snippet_approx_location_lat !== "") {
var snippetApproxLocation = new google.maps.LatLng(
p(snippet.snippet_approx_location_lat),
p(snippet.snippet_approx_location_long)
);
var marker2 = new google.maps.Marker({
position: snippetApproxLocation,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
}
});
// approximate location at corrected time from diary entry
if (d.entry_approx_location_lat !== "") {
var entryApproxLocation = new google.maps.LatLng(
p(d.entry_approx_location_lat),
p(d.entry_approx_location_long)
);
var marker3 = new google.maps.Marker({
position: entryApproxLocation,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
});
}
}
function p( string ) {
if (string === null)
return "";
else
return string;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDO_bHfTaLLr2Ugghz1hQ2QIZdRaa0SKX0"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<style type="text/css">
.map-canvas {
width: 325px;
height: 325px;
float: right;
margin: 5px;
}
</style>
<div id="map-2899_1" class="map-canvas"></div><br><br>
<div id="map-2899_3" class="map-canvas"></div>
I found workaround for what I think is a bug in WebKit. Since caching of map tiles didn't seem to be the problem, I started playing around with CSS display and position properties.
Adding display:inline-block; to my .map_canvas seems to solve the problems in the printout… The tiles are now all correct. display:inline; alone doesn't have the same effect; and I don't know why inline-block solves the problem.
(Since in my particular case I wanted the map to float:right; I had to put a wrapper around the .map_canvas div. So, .map_canvas has the display:inline-block; and the .map-container has float:right;.)
So, it seems, in WebKit, print support for multiple maps on a page is either buggy, or I'm not understanding it fully.
Here, now, is the working example page: http://matsch.binaervarianz.de/tmp/print_entries-solution.html
And this is the Print-to-PDF output of that page: http://matsch.binaervarianz.de/tmp/print_entries-solution.pdf
Here's the working code (only the HTML/CSS has changed):
// first map
var snippets = [];
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510463",
snippet_location_long: "-86.2288448"
});
var mapData_2899_1 = {
snippets: snippets,
entry_approx_location_lat: "",
entry_approx_location_long: ""
};
showMap(mapData_2899_1, "2899_1");
// second map
snippets = [];
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510639",
snippet_location_long: "-86.2287998"
});
snippets.push({
snippet_approx_location_lat: "",
snippet_approx_location_long: "",
snippet_location_lat: "39.9510739",
snippet_location_long: "-86.2288998"
});
var mapData_2899_3 = {
snippets: snippets,
entry_approx_location_lat: "",
entry_approx_location_long: ""
};
showMap(mapData_2899_3, "2899_3");
// show map function
function showMap(d, primKey) {
$( '#map-' + primKey ).addClass('map-canvas');
var mapOptions = {
center: { lat: 39.9513164, lng: -86.2274201 },
streetViewControl: false, zoom: 12,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('map-' + primKey), mapOptions);
$.each(d.snippets, function( i, snippet ) {
// location when snippet was recorded
if (snippet.snippet_location_lat !== "" && snippet.snippet_location_long !== "") {
var snippetLoc = new google.maps.LatLng(
p(snippet.snippet_location_lat),
p(snippet.snippet_location_long)
);
var marker = new google.maps.Marker({ position: snippetLoc, map: map });
}
// approximate location taking into account how long ago the event reportedly took place
if (snippet.snippet_approx_location_lat !== "") {
var snippetApproxLocation = new google.maps.LatLng(
p(snippet.snippet_approx_location_lat),
p(snippet.snippet_approx_location_long)
);
var marker2 = new google.maps.Marker({
position: snippetApproxLocation,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
}
});
// approximate location at corrected time from diary entry
if (d.entry_approx_location_lat !== "") {
var entryApproxLocation = new google.maps.LatLng(
p(d.entry_approx_location_lat),
p(d.entry_approx_location_long)
);
var marker3 = new google.maps.Marker({
position: entryApproxLocation,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
});
}
}
function p( string ) {
if (string === null)
return "";
else
return string;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDO_bHfTaLLr2Ugghz1hQ2QIZdRaa0SKX0"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<style type="text/css">
.map-container {
float: right;
margin-left: 5px;
}
.map-canvas {
width: 325px;
height: 325px;
display: inline-block;
}
</style>
<div class="map-container">
<div id="map-2899_1" class="map-canvas"></div>
</div>
<br><br>
<div class="map-container">
<div id="map-2899_3" class="map-canvas"></div>
</div>

show google map inside a jquery dialogue form

Hi i'm trying to show a map in my form inside a jquery dialogue,
my jquery dialogue return a partial view where i put this code inside #section scripts and i called also the maps api
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
// Where all the fun happens
function Initialize() {
// Google has tweaked their interface somewhat - this tells the api to use that new UI
google.maps.visualRefresh = true;
var Liverpool = new google.maps.LatLng(53.408841, -2.981397);
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 14,
center: Liverpool,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
// This makes the div with id "map_canvas" a google map
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// This shows adding a simple pin "marker" - this happens to be the Tate Gallery in Liverpool!
var myLatlng = new google.maps.LatLng(53.40091, -2.994464);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Tate Gallery'
});
// You can make markers different colors... google it up!
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
// a sample list of JSON encoded data of places to visit in Liverpool, UK
// you can either make up a JSON list server side, or call it from a controller using JSONResult
var data = [
{ "Id": 1, "PlaceName": "Liverpool Museum", "OpeningHours": "9-5, M-F", "GeoLong": "53.410146", "GeoLat": "-2.979919" },
{ "Id": 2, "PlaceName": "Merseyside Maritime Museum ", "OpeningHours": "9-1,2-5, M-F", "GeoLong": "53.401217", "GeoLat": "-2.993052" },
{ "Id": 3, "PlaceName": "Walker Art Gallery", "OpeningHours": "9-7, M-F", "GeoLong": "53.409839", "GeoLat": "-2.979447" },
{ "Id": 4, "PlaceName": "National Conservation Centre", "OpeningHours": "10-6, M-F", "GeoLong": "53.407511", "GeoLat": "-2.984683" }
];
// Using the JQuery "each" selector to iterate through the JSON list and drop marker pins
$.each(data, function (i, item) {
var marker = new google.maps.Marker({
'position': new google.maps.LatLng(item.GeoLong, item.GeoLat),
'map': map,
'title': item.PlaceName
});
// Make the marker-pin blue!
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
// put in some information about each json object - in this case, the opening hours.
var infowindow = new google.maps.InfoWindow({
content: "<div class='infoDiv'><h2>" + item.PlaceName + "</h2>" + "<div><h4>Opening hours: " + item.OpeningHours + "</h4></div></div>"
});
// finally hook up an "OnClick" listener to the map so it pops up out info-window when the marker-pin is clicked!
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
})
}
i'm calling the map inside a div :
<div id="map_canvas" style="height: 240px; border: 1px solid gray"> map here</div>
but the problem that my map is not showing in the dialogue, even though it works well in normal page
any help plz !?
I've solved this issue with the following code:
this code is on the main view, the #next is a trigger of the form to submit, and the #dialog is inside the #form.
$(function () {
datepair();
$('#dialog').dialog({
autoOpen: false,
modal: true,
height: 720,
width: 700,
resizable: false,
title: 'Verify Location',
show: "fade",
hide: "fade",
open: function (event, ui) {
var form = $('#form');
$.ajax({
url: form.attr('actoin'),
type: form.attr('method'),
data: form.serialize(),
context: this,
success: function (result) {
$(this).html(result);
}
});
}
});
$('#next').click(function (e) {
$('#dialog').dialog('open');
return false;
});
});
this code is on the partialView
$(function () {
window.$required = $('<div></div>').dialog({
autoOpen: false,
resizable: false,
modal: true,
title: 'Verity Location Error',
buttons: {
"Ok": function () {
$(this).dialog('close');
callback();
}
}
});
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (json) {
Initialize();
}
});
return false;
});
function callback() {
$('#dialog').dialog('close');
}
function Initialize() {
//init the map
}
and this is the controller
public ActionResult PartialViewMapController()
{
return PartialView();
}
Hope it not to late for you :)

How to generate url link to google map from nearbySearch() results?

With the example below,
https://google-developers.appspot.com/maps/documentation/javascript/examples/place-search
By using nearbySearch one of the place return is "John St Square Supermarket".
How do i generate a url to show "John St Square Supermarket" in full google maps?
Right now i'm generating by appending the latitude and longitude into "http://maps.google.com/?q=" which become something like http://maps.google.com/?q=123,456
but it won't show the place's name and the correct marker.
I then tried with http://maps.google.com/?q=John St Square Supermarket
Working good... until i stumble into a place name with multiple locations. For example,
http://maps.google.com/?q=SK%20Dato%27%20Abu%20Bakar
It shows multiple location but i only need one which i already know what it's latitude and longitude is.
You can add the Latitude and Longitude to the URL using the parameter ll:
https://maps.google.com/?q=pizza+hut&ll=-33.867701,151.208471
You can also specify a default zoom level for the user using the paremeter z:
https://maps.google.com/?q=pizza+hut&ll=-33.867701,151.208471&z=12
PlacesResult.url property stands for the url of Google Places.
https://developers.google.com/maps/documentation/javascript/reference#PlaceResult
So you can do like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Place Search</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<style>
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
</style>
<script>
var map;
var infowindow;
var service;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId : google.maps.MapTypeId.ROADMAP,
center : pyrmont,
zoom : 15
});
var request = {
location : pyrmont,
radius : 500,
types : ['store']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map : map,
position : place.geometry.location,
reference : place.reference,
name : place.name
});
google.maps.event.addListener(marker, 'click', onMarker_clicked);
}
function onMarker_clicked() {
var marker = this;
service.getDetails({
reference : marker.get("reference")
}, function(result) {
var html = marker.get("name");
if (result && "url" in result) {
marker.set("url", result.url);
}
if (marker.get("url")) {
html = "<a href='" + marker.get("url") + "' target=_blank>" + html + "</a>";
}
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>