Let me explain the project a bit. i have a huge list of stores with addresses (longitude and latitude and code client ....).
Now, my problem is, i must be able to filter these markers depending on CodeClient i mean to find the client in google maps based on CodeClient .
The implementation is similar to the answer I mentioned before. You should add an input for code of client and a search button. In the function where you create markers add a property 'code' for each marker marker.code = CodeClient;. When you click search button it executes the filterByCode() function. If you pass empty value it restores all markers.
Have a look at modified code
// necessary variables
var map;
var infoWindow;
var markersData = [];
var markerCluster;
var markerArray = []; //create a global array to store markers
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(32, -6),
zoom: 7,
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// create MarkerClusterer, markersArray is not populated yet
markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
// a new Info Window is created
infoWindow = new google.maps.InfoWindow();
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
// Finally displayMarkers() function is called to begin the markers creation
displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
// This function will iterate over markersData array
// creating markers with createMarker function
function displayMarkers() {
// this variable sets the map bounds according to markers position
var bounds = new google.maps.LatLngBounds();
// for loop traverses markersData array calling createMarker function for each marker
$.get("https://gist.githubusercontent.com/abdelhakimsalama/358669eda44d8d221bf58c629402c40b/raw/bae93c852669a35f0e7053e9f8d068841ddf146a/get_data_google_api", function(response) {
markersData = JSON.parse(response);
for (var i = 0; i < markersData.length; i++) {
var latlng = new google.maps.LatLng(markersData[i].Latitude, markersData[i].Longitude);
var Route = markersData[i].Route;
var Secteur = markersData[i].Secteur;
var Agence = markersData[i].Agence;
var CodeClient = markersData[i].CodeClient;
var PrecisionGPS = markersData[i].PrecisionGPS;
var Latitude = markersData[i].Latitude;
var Longitude = markersData[i].Longitude;
var BarCode = markersData[i].BarCode;
var PrenomClient = markersData[i].PrenomClient;
var NumAdresse = markersData[i].NumAdresse;
var Tel = markersData[i].Tel;
var Whatsapp = markersData[i].Whatsapp;
var NbrFrigo = markersData[i].NbrFrigo;
var OpenAm = markersData[i].OpenAm;
var CloseAm = markersData[i].CloseAm;
var OpenPm = markersData[i].OpenPm;
var ClosePm = markersData[i].ClosePm;
var OpenAmVen = markersData[i].OpenAmVen;
var CloseAmVen = markersData[i].CloseAmVen;
var OpenPmVen = markersData[i].OpenPmVen;
var ClosePmVen = markersData[i].ClosePmVen;
var OpenAmDim = markersData[i].OpenAmDim;
var CloseAmDim = markersData[i].CloseAmDim;
var OpenPmDim = markersData[i].OpenPmDim;
var ClosePmDim = markersData[i].ClosePmDim;
var IMEI = markersData[i].IMEI;
var Date_Added = markersData[i].Date_Added;
createMarker(latlng, Route, Agence, Secteur, CodeClient, PrecisionGPS, Latitude, Longitude, BarCode, PrenomClient, NumAdresse, Tel, Whatsapp, NbrFrigo, OpenAm, CloseAm, OpenPm, ClosePm, OpenAmVen, CloseAmVen, OpenPmVen, ClosePmVen, OpenAmDim, CloseAmDim, OpenPmDim, ClosePmDim, IMEI, Date_Added);
// marker position is added to bounds variable
bounds.extend(latlng);
}
// Finally the bounds variable is used to set the map bounds
// with fitBounds() function
map.fitBounds(bounds);
});
}
// This function creates each marker and it sets their Info Window content
function createMarker(latlng, Route, Agence, Secteur, CodeClient, PrecisionGPS, Latitude, Longitude, BarCode, PrenomClient, NumAdresse, Tel, Whatsapp, NbrFrigo, OpenAm, CloseAm, OpenPm, ClosePm, OpenAmVen, CloseAmVen, OpenPmVen, ClosePmVen, OpenAmDim, CloseAmDim, OpenPmDim, ClosePmDim, IMEI, Date_Added) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: CodeClient
});
marker.code = CodeClient;
markerArray.push(marker); //push local var marker into global array
// add marker to the MarkerClusterer
markerCluster.addMarker(marker);
// This event expects a click on a marker
// When this event is fired the Info Window content is created
// and the Info Window is opened.
google.maps.event.addListener(marker, 'click', function() {
var dicoFrigosDetails = {};
var HTMLtext = "";
for (var i = 1; i <= Object.keys(dicoFrigosDetails).length / 4; i++) {
HTMLtext += '';
}
// Creating the content to be inserted in the infowindow
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">Code Client : ' + CodeClient +
'</div>' + '<div class="iw_content">Précision : ' + PrecisionGPS +
'<br />Latitude : ' + Latitude +
'<br />Longitude : ' + Longitude +
'<br />Route : ' + Route +
'<br />Secteur : ' + Secteur +
'<br />Agence : ' + Agence +
'<br />Code-barres : ' + BarCode +
'<br />prenom de Client : ' + PrenomClient +
//'<br />nom Complet de Client : ' + PrenomClient + ' ' + NomClient +
'<br />Num Adresse : ' + NumAdresse +
'<br />Téléphone : ' + Tel +
'<br />Whatsapp : ' + Whatsapp +
'<br />Nbr Frigos : ' + NbrFrigo + HTMLtext +
'<br />Ouverture Matin : ' + OpenAm +
'<br />Fermeture Matin : ' + CloseAm +
'<br />Ouverture après-midi : ' + OpenPm +
'<br />Fermeture Après-midi : ' + ClosePm +
'<br />Ouverture Matin Ven : ' + OpenAmVen +
'<br />Fermeture Matin Ven : ' + CloseAmVen +
'<br />Ouverture après-midi Ven: ' + OpenPmVen +
'<br />Fermeture après-midi Ven: ' + ClosePmVen +
'<br />Ouverture Matin Dim : ' + OpenAmDim +
'<br />Fermeture Matin Dim : ' + CloseAmDim +
'<br />Ouverture après-midi Dim : ' + OpenPmDim +
'<br />Fermeture après-midi Dim : ' + ClosePmDim +
'<br />IMEI : ' + IMEI +
'<br />Date Passage : ' + Date_Added +
'</div>';
// including content to the Info Window.
infoWindow.setContent(iwContent);
// opening the Info Window in the current map and at the current marker location.
infoWindow.open(map, marker);
});
}
function filterByCode() {
var code = document.getElementById("code-client").value;
var bounds = new google.maps.LatLngBounds();
markerCluster.clearMarkers();
if (code) {
markerArray.forEach(function(marker) {
marker.setMap(null);
});
var filtered = markerArray.filter(function(marker) {
return marker.code === code;
});
if (filtered && filtered.length) {
filtered.forEach(function(marker) {
bounds.extend(marker.getPosition());
marker.setMap(map);
});
markerCluster.addMarkers(filtered);
markerCluster.redraw();
map.fitBounds(bounds);
}
} else {
markerArray.forEach(function(marker) {
bounds.extend(marker.getPosition());
marker.setMap(map);
});
markerCluster.addMarkers(markerArray);
markerCluster.redraw();
map.fitBounds(bounds);
}
}
html {
height: 100%;
background: gray;
}
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
}
#iw_container .iw_title {
font-size: 16px;
font-weight: bold;
}
.iw_content {
padding: 15px 15px 15px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>InnoTech - Map - Server</title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<div id="search-code-container">
<input id="code-client" title="Enter code" type="text" placeholder="Enter code (E.g. 511557)" value=""/>
<input id="code-client-btn" type="button" value="Search" onclick="filterByCode()" />
</div>
<div id="map-canvas" />
I hope this helps!
Related
I am using JavaScript in HTML page to display GPS locations with markers and all these GPS locations are connected
I am trying to implement a map/direction based application using Google maps V3 API. So far I have been able to display the map and show directions for two locations selected. the first one is my current location , the second one is the location of costumer (his/her information exist in my database). All the markers are being displayed in the output properly.
To get directions to a location specified by coordinates, make it a google.maps.LatLng object. To get that from your data in the select, save the coordinates as a string in the value, then parse out the latitude and longitude to create the LatLng object.
save the coordinates in the option value:
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
parse those coordinates and create a google.maps.LatLng object in the directions request:
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
console.log("selected option value=" + destination);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
// ....
proof of concept fiddle
code snippet:
var map;
var directionsService;
var directionsDisplay;
var geocoder;
var infowindow;
function init() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 6,
center: center = new google.maps.LatLng(32, -6),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions_panel'));
// Detect user location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': userLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('start').value = results[0].formatted_address
}
});
}, function() {
alert('Geolocation is supported, but it failed');
});
}
makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/358669eda44d8d221bf58c629402c40b/raw/eca59a21899fe19b1f556ff033a33dff2a6bdd0c/get_data_google_api', function(data) {
var data = JSON.parse(data.responseText);
var selectBox = document.getElementById('destination');
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
});
}
function addOption(selectBox, text, value) {
var option = document.createElement("OPTION");
option.text = text;
option.value = value;
selectBox.options.add(option);
}
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
console.log("selected option value=" + destination);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
var request = {
origin: start,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
console.log("origin:" + start);
console.log("dest:" + destination.toUrlValue(12));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
function displayLocation(rythmstu_innotec) {
var content = '<div class="infoWindow"><strong> Code Client : ' + rythmstu_innotec.CodeClient + '</strong>' +
'<br />Latitude : ' + rythmstu_innotec.Latitude +
'<br />Longitude : ' + rythmstu_innotec.Longitude +
'<br />Route : ' + rythmstu_innotec.Route +
'<br />Secteur : ' + rythmstu_innotec.Secteur +
'<br />Agence : ' + rythmstu_innotec.Agence +
'<br />prenom de Client : ' + rythmstu_innotec.PrenomClient +
'<br />Num Adresse : ' + rythmstu_innotec.NumAdresse +
'<br />GeoAdresse : ' + rythmstu_innotec.GeoAdresse +
'<br />Téléphone : ' + rythmstu_innotec.Tel +
'<br />Whatsapp : ' + rythmstu_innotec.Whatsapp +
'<br />Nbr Frigos : ' + rythmstu_innotec.NbrFrigo +
'<br />Ouverture Matin : ' + rythmstu_innotec.OpenAm +
'<br />Fermeture Matin : ' + rythmstu_innotec.CloseAm +
'<br />Ouverture après-midi : ' + rythmstu_innotec.OpenPm +
'<br />Fermeture Après-midi : ' + rythmstu_innotec.ClosePm + '</div>';
if (parseInt(rythmstu_innotec.Latitude) == 0) {
geocoder.geocode({
'GeoAdresse': rythmstu_innotec.GeoAdresse
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.rythmstu_innotec,
title: rythmstu_innotec.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(rythmstu_innotec.Latitude), parseFloat(rythmstu_innotec.Longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: rythmstu_innotec.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
body {
font: normal 14px Verdana;
}
h1 {
font-size: 24px;
}
h2 {
font-size: 18px;
}
#sidebar {
float: right;
width: 30%;
}
#main {
padding-right: 15px;
}
.infoWindow {
width: 220px;
}
<title>MAP itinéraire </title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<body onload="init();">
<form id="services">
Location: <input type="text" id="start" value="Midar" /> Destination:
<select id="destination" onchange="calculateRoute();"></select>
<input type="button" value="afficher la direction" onclick="calculateRoute();" />
</form>
<section id="sidebar">
<div id="directions_panel"></div>
</section>
<section id="main">
<div id="map_canvas" style="width: 70%; height: 750px;"></div>
</section>
</body>
I have two listeners, one for user clicks and one for "insert_at". I want to implement a self-completion polygon. So initially the user will click to draw a polygon. When the user is drawing the polygon, I don't want to trigger the "insert_at" listener. After the polygon is completed, I want the "insert_at" listener to be triggered. How do I do that? My code snippets below:
var poly;
var map;
var markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {lat: 3.165236, lng: 101.654315} //choose an appropriate center for the map
});
poly = new google.maps.Polygon({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3,
editable: true
});
poly.setMap(map);
map.addListener('click', addLatLng);
google.maps.event.addListener(poly.getPath(), 'insert_at', function(index, obj) {
var path = poly.getPath();
//Only insert if it's not the last coordinate
if ($("#polygon-coordinates").find("div.nested-fields ").eq(index).length > 0) {
$("#polygon-coordinates").find("div.nested-fields").eq(index - 1).after('<div class="nested-fields row"></br><div class="col-xs-6"></br><label>Latitude</label></br><input class="form-control" id=""area[polygon_coordinates_attributes][' + index + '][latitude]" name="area[polygon_coordinates_attributes][' + index + '][latitude]" value="' + path.b[index].lat() + '"></div>' +
'<div class="col-xs-6"></br><label>Longitude</label></br><input class="form-control" name="area[polygon_coordinates_attributes][' + index + '][longitude]" name="area[polygon_coordinates_attributes][' + index + '][longitude]" value="' + path.b[index].lng() + '"></div></br></div>');
addMarker(path.b[index], index);
}
});
google.maps.event.addListener(poly.getPath(), 'set_at', function(index, obj) {
var path = poly.getPath();
var lat = "area[polygon_coordinates_attributes][" + index + "][latitude]";
var lng = "area[polygon_coordinates_attributes][" + index + "][longitude]";
$("input[name='" + lat + "']").val(path.b[index].lat());
$("input[name='" + lng + "']").val(path.b[index].lng());
//delete existing marker here
deleteMarker(index);
debugger
addMarker(path.b[index], index);
});
}
function isNotDupMarker(path, index) {
//check if the coordinates are duplicated
if (markers[index - 1] !== undefined && path[index].lat() !== markers[index - 1].position.lat()) {
return true;
} else {
return false;
}
}
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
markers.push(marker);
}
function deleteMarker(index) {
markers[index].setMap(null);
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
var index = path.push(event.latLng);
var i = index - 1
addMarker(event.latLng, index);
$("#polygon-coordinates").append('<div class="nested-fields row"></br><div class="col-xs-6"></br><label>Latitude</label></br><input class="form-control" id=""area[polygon_coordinates_attributes][' + i + '][latitude]" name="area[polygon_coordinates_attributes][' + i + '][latitude]" value="' + path.getAt(index - 1).lat() + '"></div>' +
'<div class="col-xs-6"></br><label>Longitude</label></br><input class="form-control" name="area[polygon_coordinates_attributes][' + i + '][longitude]" name="area[polygon_coordinates_attributes][' + i + '][longitude]" value="' + path.getAt(index - 1).lng() + '"></div></br></div>');
}
I have a lot of markers on a single map, added in a for loop. I managed to make the infoWindows display as intended, but I have one problem - they won't close when the close button is clicked.
If I open a new one, the old one closes, which is good. I even managed to make it close when the user clicks anywhere else on the map.
I've been searching for a solution, but I haven't found anything. Ideally I would like to make the close button work, but I guess it'd be good enough if I could just hide it.
Here's some code:
Adding a marker:
function addMarker( map, lat, lon, title, center, image, link )
{
// create latlng object
var latLng = new google.maps.LatLng( parseFloat( lat ), parseFloat( lon ) );
// set image base URL
var imageBase = ajax_vars.home_url + '/images/map-markers/';
// set default image
if ( typeof( image ) == 'undefined' )
image = 'default';
// CREATE MAPS OBJECTS FOR THE MARKER
// main image
var icon = new google.maps.MarkerImage(
imageBase + image + '.png',
new google.maps.Size(32, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32)
);
// shadow
var shadow = new google.maps.MarkerImage(
imageBase + image + '.shadow.png',
new google.maps.Size(32, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32)
);
// shape
var shape = {
coord: [1, 1, 1, 32, 32, 32, 32 , 1],
type: 'poly'
};
// ADD MARKER
marker = new google.maps.Marker({
position: latLng,
title: title,
map: map,
shadow: shadow,
icon: icon,
shape: shape
});
// ADD INFOWINDOW TO MARKER
addInfoWindowToMarker( marker, title, link );
// CENTER MARKER IF REQUIRED
if ( center )
map.setCenter( latLng );
}
Adding info window:
function addInfoWindowToMarker( marker, title, link )
{
// WINDOW HTML CONTENT
// link html
if ( typeof( link ) == 'undefined' )
link = '';
else
link = "(<a href='" + link + "'>click to view</a>)";
// window html
var htmlContent = "<div class='infoWindow'>This is content for "
+ title
+ "<br/>"
+ link
+ "</div>"
// create object
infowindow = new google.maps.InfoWindow();
// CLICK EVENT LISTENER
google.maps.event.addListener( marker, 'click', function() {
infowindow.setContent( htmlContent ),
infowindow.open( map, marker ),
// trying to hide the button
// $( '.infoWindow' ).parent().parent().siblings().find( 'img' ).hide();
//$( '[src="http://maps.gstatic.com/mapfiles/mv/imgs8.png"]' ).hide();
});
// trying to close the winddow on click
google.maps.event.addListener( infowindow, 'closeclick', function(){
infowindow.open( null, null );
alert('closing');
});
}
The closeclick event is not even fired when I click the button.
The attempts to hide the button did nothing.
I get an error which I don't understand when I click on the marker :
Uncaught TypeError: Object # has no method 'M'
You can check out the map here.
I ran into something similar: the close button wasn't causing the infoWindow to close. In my case, the value of the map argument wasn't the correct element (it was a wrapper/container).
Once I passed the correct element, everything worked as expected.
Please refer the following example which i have used already.,
Step #1 : Include the Three script Files in header of your page.,like
(i). <script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=Your_API_KEY"></script>
(ii).<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
(iii).<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
Step #2 : Scripts On Page
<script type="text/javascript">
//initialize the map window
jQuery(document).ready(function () {
load();
});
jQuery(window).unload(function () {
GUnload();
});
var map;
var geocoder;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function load() {
if (GBrowserIsCompatible()) {
geocoder = new GClientGeocoder();
map = new GMap2(document.getElementById('map'));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
//map.setCenter(new GLatLng(35.048629,-0.820663), 4);
searchLocations();
document.getElementById('directions-panel').innerHTML = '';
var url_new = ''+ benObj.TEMPLATE_DIR +'/print.html';
var print_icon_url_new = 'PrintLink';
jQuery('#print_icon').html(print_icon_url_new);
}
}
//Search Locations with address input
function searchLocations() {
var address = document.getElementById('addressInput').value;
// alert(address);
var address_new = jQuery("#addressInput_new").val();
if (address_new != "Enter City or Zip") {
jQuery("#loc1").html(address_new);
}
geocoder.getLatLng(address, function (latlng) {
//alert(latlng);
if (!latlng) {
alert(address + ' not found');
} else {
searchLocationsNear(latlng);
}
});
}
// Search Near By Location to place the Markers and Information windows
function searchLocationsNear(center) {
var radius = document.getElementById('radiusSelect').value;
var searchUrl = ''+ benObj.BASE_ROOT +'/mapmarker?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&format=raw';
jQuery.get(searchUrl, function (data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
var sidebar = document.getElementById('sidebar');
var sidebar_val = '';
//sidebar.innerHTML = 'Results Found';
jQuery("#sidebar").html(sidebar_val);
<!--jQuery("#loc_count").html(markers.length);-->
if (markers.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new GLatLng(35.048629, -0.820663), 4);
return;
}
var bounds = new GLatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var phone_new = markers[i].getAttribute('phonenumber');
var distance = parseFloat(markers[i].getAttribute('distance'));
var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
var markerchar = "b";
var marker = createMarker(point, name, address, phone_new);
map.addOverlay(marker);
// var location_count = jQuery('#loc_count').val();
jQuery('#loc_count').val(i + 1);
var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone_new);
jQuery('#sidebar').append(sidebarEntry);
//sidebar.appendChild(sidebarEntry);
// ScrollPane.getContentPane().appendChild(sidebarEntry);
bounds.extend(point);
}
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
jQuery('#sidebar').jScrollPane();
//jQuery('#sidebar').reinitialise();
});
}
//To Create a Marker With Information Window
function createMarker(point, name, address, phone_new) {
var pinkIcon = new GIcon(G_DEFAULT_ICON);
pinkIcon.image = ""+ benObj.IMAGE_DIR +"addr-pin-1.png";
var markerOptions = {
icon: pinkIcon
};
var marker = new GMarker(point, markerOptions);
var event_calendar = "event_calendar";
var event_title = ""+ benObj.event_title +"";
var display = "block";
var e_dt_start = jQuery("#dtstart").val();
var e_dt_end = jQuery("#dtend").val();
var e_start_timestamp = (formatTimestring(e_dt_start));
var e_end_timestamp = (formatTimestring(e_dt_end));
var e_desc = jQuery("#edesc").val();
var StrippedString = e_desc.replace(/(<([^>]+)>)/ig, "");
var trimmed = StrippedString.replace(/^\s+|\s+$/g, '');
var html = '<b>' + name + '</b> <br/>' + address + '<br>contact: ' + phone_new + '<br><br>Add to Calendar<div class="summary" style="display:none;">' + event_title + ' - "' + name + '"</div><span class="dtstart date" title="' + e_dt_start + '" style="display:none;">8th Aug 2010</span><span class="dtend date" title="' + e_dt_end + '" style="display:none;">01:30am - 12:00pm</span><div class="event-desc" style="display:none;">' + trimmed + '</div><div class="event-locate" style="display:none;">' + name + ',' + address + '</div> | Remind Me<br><br>Get Direction From:<br><input type="hidden" id="start" value="' + address + '"><input type="text" id="end" value="" style="border: 1px solid #ECE6D5;"> <input type="button" value="GO" onclick="calcRoute();" style="border: 1px solid #ECE6D5;padding-left:5px;">';
GEvent.addListener(marker, 'click', function () {
marker.openInfoWindowHtml(html);
//jQuery(this).addtocal();
});
return marker;
}
// To Make Sidebar Entry If need
function createSidebarEntry(marker, name, address, distance, phone_new) {
var div = document.createElement('div');
var html = '<div class="locrow clearfix"><div class="left" style="width:240px;"><span class="count" id="loc_count">' + jQuery("#loc_count").val() + '</span><address><strong>' + name + '</strong>' + address + '</address><span class="mapdate"><span class="icon date"></span>'+ benObj.event_start_month_date +' – '+ benObj.event_end_month_date_year +'</span></div><div class="right" style="width:154px;"><ul><li><span class="icon phone"></span>' + phone_new + '</li><li><span class="icon time"></span>11 am – 7 pm</li><li><span class="icon car"></span>distance ' + distance.toFixed(1) + ' mi</li></ul></div></div>';
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
GEvent.addDomListener(div, 'click', function () {
GEvent.trigger(marker, 'click');
});
GEvent.addDomListener(div, 'mouseover', function () {
div.style.backgroundColor = '#eee';
});
GEvent.addDomListener(div, 'mouseout', function () {
div.style.backgroundColor = '#fff';
});
return div;
}
// To make a Directions If need
function calcRoute() {
directionsDisplay = new google.maps.DirectionsRenderer();
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var url = "http://maps.google.co.in/maps?f=d&source=s_d&saddr=" + start + "&daddr=" + end + "&aq=0&vpsrc=0&hl=en&doflg=ptm&mra=ls&ie=UTF8&t=m&z=5&layer=c&pw=2";
var print_icon_url = 'PrintLink';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
directionsDisplay.setDirections(response);
jQuery('#print_icon').html(print_icon_url);
}
});
}
</script>
Step #3: To Create a XML For Markers and Information Windows
<?php
function mapMarker($center_lat,$center_lng,$radius)
{
$mysqli = $this->_getMySqlConnection();
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Search the rows in the markers table
$query = sprintf("SELECT phone,street_address_1, store_name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < '%s' ORDER BY distance LIMIT 0 , 10",
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($center_lng),
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($radius));
$result = $mysqli->query($query);
header("Content-type: text/xml");
header('Access-Control-Allow-Origin: *');
$avoid_duplicate="";
// Iterate through the rows, adding XML nodes for each
while ($row = #$result->fetch_assoc())
{
if($avoid_duplicate!=$row['store_name'])
{
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['store_name']);
$newnode->setAttribute("address", $row['street_address_1']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
$newnode->setAttribute("phonenumber", $row['phone']);
$avoid_duplicate=$row['store_name'];
}
}
$outXML=$dom->saveXML();
$result->close();
$mysqli->close();
return $outXML;
}
?>
Step #4: HTML Part
<div class="mapleft">
<div class="ScrollPane scroll-pane" id="sidebar" style="overflow: auto; height: 430px;"></div>
<div class="mapshadow"></div>
</div>
<input type="hidden" id="addressInput" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect" value="50" />
<input type="hidden" id="addressInput_temp" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect_temp" value="50" />
<input type="hidden" name="X_REQUESTED_WITH" value="XMLHttpRequest" />
<div class="mapright">
<div id="map" style="width: 475px; height: 450px"></div>
</div>
<div class="map-dir" id="directions-panel" style="float:right;width:488px;"></div>
<input type="hidden" id="loc_count" value="1" />
These are the things which will produce the great out comes. I think this may help you to resolve your problem.
At first sight, you are using commas instead of semicolons in your click handler:
google.maps.event.addListener( marker, 'click', function() {
infowindow.setContent( htmlContent ), ---> HERE
infowindow.open( map, marker ), ---------> AND HERE
Try replacing those for semicolons ; as that could probably be the error you are having.
UPDATE:
In your infowindow closeclick handler, replace your following line:
infowindow.open( null, null );
for this one:
infowindow.close();
As close() is the method normally used to close infowindows.
I need to draw colored polygons over certain German states. What's the best way (or easiest, fastest, any really...) to do this? Do I need to somehow get all the outlines as lat/lon points and draw a polygon based on those? Or is there a better way?
You want to do something like this?
http://www.geocodezip.com/geoxml3_test/v3_FusionTables_query_sidebarF_local.html?country=Germany
It uses publicly available data in FusionTables, the Natural Earth Data set.
encrypted ID:
https://www.google.com/fusiontables/DataSource?docid=19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA
numeric ID:
https://www.google.com/fusiontables/DataSource?dsrcid=420419
You can style them (color them) as you like.
code snippet:
// globals
var map = null;
var infoWindow = null;
var geoXml = null;
var geoXmlDoc = null;
var myLatLng = null;
var myOptions = null;
var mapCenter = null;
var geocodeTheCountry = true;
var gpolygons = [];
// Fusion Table data ID
var FT_TableID = "19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA"; // 420419;
var CountryName = "Germany";
google.load('visualization', '1', {
'packages': ['corechart', 'table', 'geomap']
});
function createSidebar() {
// set the query using the parameters
var FT_Query2 = "SELECT 'name_0', 'name_1', 'kml_4326' FROM " + FT_TableID + " WHERE name_0 = '" + CountryName + "' ORDER by 'name_1'";
var queryText = encodeURIComponent(FT_Query2);
// alert("createSidebar query="+FT_Query2);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(getData);
}
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(createSidebar);
var FTresponse = null;
myLatLng = new google.maps.LatLng(37.422104808, -122.0838851);
// these set the initial center, zoom and maptype for the map
// if it is not specified in the query string
var lat = 37.422104808;
var lng = -122.0838851;
var zoom = 18;
var maptype = google.maps.MapTypeId.ROADMAP;
if (!isNaN(lat) && !isNaN(lng)) {
myLatLng = new google.maps.LatLng(lat, lng);
}
infoWindow = new google.maps.InfoWindow();
//define callback function, this is called when the results are returned
function getData(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
fusiontabledata = "<table><tr>";
fusiontabledata += "<th>" + response.getDataTable().getColumnLabel(1) + "</th>";
// }
fusiontabledata += "</tr><tr>";
for (i = 0; i < numRows; i++) {
fusiontabledata += "<td><a href='javascript:myFTclick(" + i + ")'>" + response.getDataTable().getValue(i, 1) + "</a></td>";
// }
fusiontabledata += "</tr><tr>";
}
fusiontabledata += "</table>";
//display the results on the page
document.getElementById('sidebar').innerHTML = fusiontabledata;
}
function infoWindowContent(name, description) {
content = '<div class="FT_infowindow"><h3>' + name +
'</h3><div>' + description + '</div></div>';
return content;
}
function myFTclick(row) {
var description = FTresponse.getDataTable().getValue(row, 0);
var name = FTresponse.getDataTable().getValue(row, 1);
if (!gpolygons[row]) {
var kml = FTresponse.getDataTable().getValue(row, 2);
// create a geoXml3 parser for the click handlers
var geoXml = new geoXML3.parser({
map: map,
zoom: false,
infoWindow: infoWindow,
singleInfoWindow: true
});
geoXml.parseKmlString("<Placemark>" + kml + "</Placemark>");
geoXml.docs[0].gpolygons[0].setMap(null);
gpolygons[row] = geoXml.docs[0].gpolygons[0].bounds.getCenter();
}
var position = gpolygons[row];
if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
infoWindow.setOptions({
content: infoWindowContent(name, description),
pixelOffset: new google.maps.Size(0, 2),
position: position
});
infoWindow.open(map);
}
function initialize() {
myOptions = {
zoom: zoom,
center: myLatLng,
mapTypeId: maptype
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var geocoder = new google.maps.Geocoder();
if (geocoder && geocodeTheCountry) {
geocoder.geocode({
'address': CountryName + " Country"
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
var FT_Query = "SELECT 'kml_4326' FROM " + FT_TableID + " WHERE 'name_0' = '" + CountryName + "';";
var FT_Options = {
suppressInfoWindows: true,
query: {
from: FT_TableID,
select: 'kml_4326',
where: "'name_0' = '" + CountryName + "';"
},
styles: [{
polygonOptions: {
fillColor: "#FF0000",
fillOpacity: 0.35
}
}]
};
layer = new google.maps.FusionTablesLayer(FT_Options);
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(event) {
infoWindow.close();
infoWindow.setContent(infoWindowContent(event.row.name_1.value, event.row.name_0.value));
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
width: 300px;
height: 100%
}
.infowindow * {
font-size: 90%;
margin: 0
}
<script src="https://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script src="http://www.google.com/jsapi"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<table style="width:100%; height:100%;">
<tr style="width:100%; height:90%;">
<td style="width:60%; height:100%;">
<div id="map_canvas"></div>
</td>
<td>
<div id="sidebar" style="width:300px;height:400px; overflow:auto"></div>
</td>
</tr>
</table>
Also, you could take a look at the Google GeoChart API, which is not that feature-rich but pretty easy to use. Try the following code in the API playground:
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Province', 'Popularity'],
['Bremen', 100],
['Niedersachsen', 900],
['Saksen', 700],
['Saarland', 300],
['Bayern', 400]
]);
var options = {
region: 'DE',
displayMode: 'regions',
colorAxis: {colors: ['green', 'blue']},
resolution:'provinces'
};
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
geochart.draw(data, options, {width: 556, height: 347});
}
i've started very enthousiastic with google maps and managed to get the info from my mysql dbase to the map on my site. The problem i'm facing now is that i want to be able to click through from the info window to a page on my site (the link also comes out of the dbase).
Here is the standard google api code I'm using now ('mijnlink' is the link), i've tried a lot of different things but so far no solution, hope you can help me to find the answer:
GDownloadUrl("../phpsqlajax_genxml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var mijnlink = markers[i].getAttribute("mijnlink");
var naam = markers[i].getAttribute("naam");
var address = markers[i].getAttribute("address");
var hotelcampingbungalow = markers[i].getAttribute("hotelcampingbungalow");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, mijnlink, naam, address, hotelcampingbungalow);
map.addOverlay(marker);
}
});
function createMarker(point, mijnlink, naam, address, hotelcampingbungalow) {
var marker = new GMarker(point, customIcons[hotelcampingbungalow]);
var html = "<b>" + mijnlink + hotelcampingbungalow + " " + naam + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
Got some other help, the var html in the Createmarker function must be like this:
var html = "<b><a href='" + mijnlink + "'>klik hier</a>" + hotelcampingbungalow + " " + naam + "</b> <br/>" + address;