Duplicate values in google map pagination - javascript

The code below display a map and display the results in UL. I have 2 buttons that display train station and shopping mall.Initially, it will display the results correctly but If I click the other button, it will display duplicate values.
Javascript
var map;
var pos;
var distance;
var distancearray = [];
var markers = [];
//=================================================================
function initialize() {
googleMapsLoaded = false;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13
});
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var request = {
location:pos,
radius:3000, //3000 Meters
type:initialtype
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'You Are Here',
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function callback(results, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
else{
for (var i = 0; i < results.length; i++)
markers.push(createMarker(results[i]));
}
} //end callback function
/* listen to the tilesloaded event
if that is triggered, google maps is loaded successfully for sure */
google.maps.event.addListener(map, 'tilesloaded', function() {
googleMapsLoaded = true;
// document.getElementById("mapnotification").innerHTML = "Map Loaded!";
$("#mapnotification").hide();
$("#map-loaded").show();
$("#map-loaded").css('visibility', 'hidden');
$("#map-notloaded").hide();
//clear the listener, we only need it once
google.maps.event.clearListeners(map, 'tilesloaded');
});
setTimeout(function() {
if (!googleMapsLoaded) {
//we have waited 7 secs, google maps is not loaded yet
document.getElementById("mapnotification").innerHTML = "Map NOT Loaded! Make sure you have stable internet connnection";
$("#mapnotification").hide();
$("#map-notloaded").show();
$("#map-loaded").hide();
}
}, 7000);
function createMarker(place) { // Create Marker and the Icon of the marker
// var bounds = new google.maps.LatLngBounds();
var markerlat;
var markerlon;
var p2;
var output="";
var placesList = document.getElementById('places');
placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8,
fillColor:'00a14b',
fillOpacity:0.3,
fillStroke: '00a14b',
strokeWeight:4,
strokeOpacity: 0.7
}, // end icon
}); //end of marker variable
markerlat = marker.getPosition().lat()
markerlon = marker.getPosition().lng()
console.log("Markers Lat" + markerlat);
console.log("Markers Lon" + markerlon );
p2 = new google.maps.LatLng(markerlat, markerlon);
distance = [calcDistance(pos, p2)];
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
distancearray.push([distance, place.name]);
distancearray.sort();
console.log("distancearraylength" + distancearray.length);
console.log("Summary" + distancearray);
for(var i = 0; i < distancearray.length; i++){
output += '<li>' + distancearray[i][1] + " " + distancearray[i][0]+ " " + "km" + '</li>';
placesList.innerHTML = output;
}
google.maps.event.addListener(marker, 'click', function() { //show place name when marker clicked
infowindow.setContent(place.name);
infowindow.open(map, marker);
}); // end of marker show place name
} // end createMarker function
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
} // End handleNoGeolocation function
} //End function initialize
//==========================================================================================================//
$(document).on('pagebeforeshow','#itemPanel2', function(e, data){ // Loading of Nearest Place Options
bindchoicesclick();
function bindchoicesclick(){
$("#subway_station").on("click",function(){
// alert("subway");
markers = [];
pos="";
while(distancearray.length > 0) {
distancearray.pop();
}
while(markers.length > 0) {
markers.pop();
}
//$("#places").empty();
initialtype = ['subway_station'];
buttonholder = "Nearest Station";
$("#find").val(buttonholder);
$("#find").button("refresh");
initialize();
});
$("#shopping_mall").on("click",function(){
// alert("stores");
markers = [];
pos="";
while(distancearray.length > 0) {
distancearray.pop();
}
while(markers.length > 0) {
markers.pop();
}
// distancearray.splice(0).
// $("#places").empty();
initialtype = ['shopping_mall'];
buttonholder = "Nearest Mall";
$("#find").val(buttonholder);
$("#find").button("refresh");
initialize();
});
}
});
HTML
<h1 id="headerField">Nearby Search</h1>
</div>
Search Nearest Train Station
Search Nearest Mall
</div>
<!--Train Stations -->
<div id="globa_map" data-role="page">
<div data-role="header">
Back
Refresh
<h1 id="headerField">Global</h1>
</div>
<div data-role="content">
<!-- <input type="button" id="refreshmap" value="Refresh"> -->
<p id="mapnotification">Please wait while the map is loading...</p>
<p id="map-loaded">Map Loaded!</p>
<p id="map-notloaded">Map NOT Loaded! Make sure you have stable internet connnection</p>
<h2>Results</h2>
<ul id="places"></ul>
<button id="more">More results</button>
<div id="map" style="height:400px;">
</div>
</div>

Related

Laravel fetch longitude and latitude from database and display markers on Google Map

Hello guys I need help from you. I'm coding a web application using laravel framework. I've recorded logitudes, latitudes and other informations in the database. I want to fetch those informations and display their marker on google map. All examples I'm getting are for PHP scratch code. Is there anyone who can help me how to do it in laravel?
HERE IS THE DATABASE CODE
Schema::create('alertes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('code');
$table->string('code_client');
$table->string('client_category');
$table->string('longitude');
$table->string('latitude');
$table->timestamps();
});
HERE IS MY BLADE FILE
<div id="map" style="width:100%;height:400px;"></div>
</div>
</div>
</div>
</div>
#endsection()
#section('custom-script')
<script type="text/javascript" src="{{asset('assets')}}/map/carte_alertes.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCnyJJ2gorvX0rsuhBJLNUsfyioWSSep2Q&callback=init"></script>
<script>
</script>
#endsection
HERE IS MY SCRIPT.JS
<script>
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var map;
// Beni
var center = new google.maps.LatLng(0.496422, 29.4751);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function init() {
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
makeRequest("{{route('alertes.index')}}", function (data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
}
// displayLocation method
function displayLocation(location) {
var content = '<div class="infoWindow"><strong>' + location.code_client + '</strong>'
+ '<br/>' + location.client_category + '</div>';
if (parseInt(location.latitude) == 0) {
geocoder.geocode({'client_category': location.client_category}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(location.latitude), parseFloat(location.longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
change callback=initMap not callback=init
src="https://maps.googleapis.com/maps/api/js?key=yourapikey&callback=init"></script>
try your data format this way
public function mapMarker(){
$locations = Alerte::all();
$map_markes = array ();
foreach ($locations as $key => $location) {
$map_markes[] = (object)array(
'code' => $location->code,
'code_client' => $location->code_client,
'client_category' => $location->client_category,
'longitude' => $location->longitude,
'latitude' => $location->latitude,
);
}
return response()->json($map_markes);
}
copy this code and re-place this code
content : `<div><h5>${Number(datas[index].latitude)}</h5><p><i class="icon address-icon"></i>${Number(datas[index].longitude)}</p></div>`
Still having the problem
HERE IS MY NE
function initMap(){
var mapElement = document.getElementById('map');
var url = '/map-marker';
async function markerscodes(){
var data = await axios(url);
var alerteData = data.data;
mapDisplay(alerteData);
}
markerscodes();
function mapDisplay(datas) {
//map otions
var options ={
center :{
lat:Number(datas[0].latitude), lng:Number(datas[0].longitude)
},
zoom : 10
}
//Create a map object and specify the DOM element for display
var map = new google.maps.Map(mapElement, options);
var markers = new Array();
for (let index = 0; index < datas.length; index++){
markers.push({
coords: {lat: Number(datas[index].latitude), lng:Number(datas[index].longitude)},
content : '<div><h5>${datas[index].code_du_suspect}</h5><p><i class="icon address-icon"></i>${datas[index].etat_du_suspect}</p></div>'
})
}
//looping through marker
for (var i = 0; i < markers.length; i++){
//une fontion a creer si dessous
addMarker(markers[i]);
}
function addMarker(props){
var marker = new gooogle.maps.Marker({
position : props.coords,
map: map
});
if(props.iconImage){
marker.setIcon(props.iconImage);
}
if(props.content){
var infoWindow = new google.maps.infoWindow({
content : props.content
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
}
}
}
}

Going over quota on Google Maps Api

So I am trying to make a simple application that will allow the user to search for restaurants and have the results show as markers on the map and as text below. The results object that returns from the textSearch doesn't provide detailed information like: phone number, pictures, etc. So i decided to create an array of place id's pushed from the results object, get the place details for each id, then push that into an array. The problem I get is a message from google saying I'm over my quota and I think it's because I'm requesting the place details for every single search result.
Is there a way I can request the place details only for the marker I click? Or is there a better solution to my problem? Thank you in advance for your help.
<!DOCTYPE html>
<html>
<head>
<title>gMap test</title>
<style type="text/css">
#map-canvas{
height:500px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript">
function performSearch(){
var locationBox;
var address = document.getElementById("address").value;
var searchRadius = metricConversion(document.getElementById("radius").value);
//gMaps method to find coordinates based on address
geocoder.geocode({'address':address}, function(results,status){
if(status == google.maps.GeocoderStatus.OK){
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map:map,
position: results[0].geometry.location
});
var latitude = results[0].geometry.location.A;
var longitude = results[0].geometry.location.F;
locationBox = new google.maps.LatLng(latitude, longitude);
}else{
errorStatus(status);
return;
}
//search request object
var request = {
query: document.getElementById('keyword').value,
location: locationBox,
radius: searchRadius,
//minPriceLvl: minimumPrice,
//maxPriceLvl: maximumPrice,
types: ["restaurant"]
}
//search method. sending request object and callback function
service.textSearch(request, handleSearchResults);
});
};
var latLngArray = [];
var placeIdArray = [];
//callback function
function handleSearchResults(results,status){
if( status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
placeIdArray.push(results[i].place_id)
latLngArray.push(results[i].geometry.location);
};
for(var j = 0; j<placeIdArray.length; j++){
service.getDetails({placeId: placeIdArray[j]},getDetails)
};
}
else{errorStatus(status)};
};
var detailedArray = [];
function getDetails(results,status){
if (status == google.maps.places.PlacesServiceStatus.OK) {
detailedArray.push(results);
for(var i = 0; i<detailedArray.length; i++){
createMarker(detailedArray[i],i);
}
}
else{
errorStatus(status)
};
}
//array of all marker objects
var allMarkers = [];
//creates markers and info windows for search results
function createMarker(place, i) {
var image = 'images/number_icons/number_'+(i+1)+'.png';
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
html:
"<div class = 'markerPop'>" + "<h3>" + (i+1) + ". " + place.name + "</h3><br>" + "<p>Address: "
+ place.formatted_address + "</p><br>" + "<p> Price Range: "+ priceLevel(place.price_level)
+ "</p>" + "</div>",
icon: image
});
allMarkers.push(marker);
marker.infowindow = new google.maps.InfoWindow();
//on marker click event do function
google.maps.event.addListener(marker, 'click', function() {
//service.getDetails({placeId: placeIdArray[j]},getDetails)
//sets infowindow content and opens infowindow
infowindow.setContent(this.html);
infowindow.open(map,this);
});
//create new bounds object
var bounds = new google.maps.LatLngBounds();
//iterates through all coordinates to extend bounds
for(var i = 0;i<latLngArray.length;i++){
bounds.extend(latLngArray[i]);
};
//recenters map around bounds
map.fitBounds(bounds);
};
var map;
var service;
var geocoder;
var infowindow;
function initialize(location){
var mapOptions = {
center: new google.maps.LatLng(37.804, -122.271),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
service = new google.maps.places.PlacesService(map)
infowindow = new google.maps.InfoWindow();
};
$(document).ready(function(){
initialize();
$('#search').on('click', function(){
removeMarkers();
performSearch();
});
});
//::::::Random Functions:::::::
//Clears all markers between searches
function removeMarkers(){
for(var i = 0; i<allMarkers.length;i++){
allMarkers[i].setMap(null);
};
};
//converts miles to meters for search object
function metricConversion(miles){
var meters;
meters = miles * 1609.34;
return meters;
}
//converts number value to $ sign
function priceLevel(number){
var moneySigns = ""
for(var i =0;i<=number;i++){
moneySigns += "$";
};
return moneySigns;
}
//errors for search results
function errorStatus(status){
switch(status){
case "ERROR": alert("There was a problem contacting Google Servers");
break;
case "INVALID_REQUEST": alert("This request was not valid");
break;
case "OVER_QUERY_LIMIT": alert("This webpage has gone over its request quota");
break;
case "NOT_FOUND": alert("This location could not be found in the database");
break;
case "REQUEST_DENIED": alert("The webpage is not allowed to use the PlacesService");
break;
case "UNKNOWN_ERROR": alert("The request could not be processed due to a server error. The request may succeed if you try again");
break;
case "ZERO_RESULTS": alert("No result was found for this request. Please try again");
break;
default: alert("There was an issue with your request. Please try again.")
};
};
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="searchBar">
<h3>search options</h3>
Location:<input type="text" id="address" value="enter address here" /><br>
Keyword<input type="text" id="keyword" value="name or keyword" /><br>
Advanced Filters:<br>
Search Radius:<select id="radius">
<option>5</option>
<option>10 </option>
<option>15 </option>
<option>20 </option>
<option>25 </option>
</select>miles<br>
<div id="minMaxPrice">
Min Price<select id="minPrice">
<option>$</option>
<option>$$</option>
<option>$$$</option>
<option>$$$$</option>
</select>
Max Price<select id="maxPrice">
<option>$</option>
<option>$$</option>
<option>$$$</option>
<option>$$$$</option>
</select>
</div>
<input type="button" id="search" value="Submit Search"/><br>
</div>
<div id='searchResults'>
</div>
</body>
</html>
The radarSearch example in the documentation requests the details of the marker on click.
code snippet:
var map;
var infoWindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-33.8668283734, 151.2064891821),
zoom: 15,
styles: [{
stylers: [{
visibility: 'simplified'
}]
}, {
elementType: 'labels',
stylers: [{
visibility: 'off'
}]
}]
});
infoWindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
keyword: 'best view'
};
service.radarSearch(request, callback);
}
function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
createMarker(result);
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
// Star
path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
fillColor: '#ffff00',
fillOpacity: 1,
scale: 1 / 4,
strokeColor: '#bd8d2c',
strokeWeight: 1
}
});
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(place, function(result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var htmlStr = "<b>"+result.name+"</b><br>";
if (result.website) htmlStr += "<a href='"+result.website+"'>"+result.website+"</a><br>";
if (result.adr_address) htmlStr += result.adr_address+"<br>";
infoWindow.setContent(htmlStr);
infoWindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<div id="map-canvas"></div>
I had the same issue some time ago. The geocoding function by google is done in order to avoid the user executing it on a large set of data (and then, avoid you to get a large amount of geocoded address easily).
My solution was to execute the geocoding function only when the user choose a particular place, and then, display this particular data (handled by the click on the pin).
I think it would be very useful to initiate a jsfiddle with a working version of your code.
Basically on your function :
google.maps.event.addListener(marker, 'click', function() {
//Execute geocoding function here on marker object
//Complete your html template content
infowindow.setContent(this.html);
infowindow.open(map,this);
});

Different results in Google Places API and Google Maps

I'm using the Google Places JavaScript API for a desktop application. However, the search results returned by the API aren't the same as the ones I get in maps.google.com. For instance, if I search for "Antique Hostel", I get many results (almost all of them are kinda random) whereas on Google Maps I get the correct (single) result.
Is the quality of the search isn't the same in the API and the service?
Here is my code
function initialize() {
// map setup
var mapOptions = {
center: new google.maps.LatLng(52.519171, 13.406091199999992),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
$map = document.getElementById('mapCanvas'),
map = new google.maps.Map($map, mapOptions),
input = document.getElementById('searchInput'),
autocomplete = new google.maps.places.Autocomplete(input),
service = new google.maps.places.PlacesService(map),
$ajaxSearchInput = $(input),
markers = [];
autocomplete.bindTo('bounds', map);
$ajaxSearchInput.keydown(function(e) {
if (e.keyCode === 13) {
var request = {
query: $(this).val(),
radius: '500',
location: map.getCenter()
}
service.textSearch(request, searchCallBack);
}
});
searchCallBack = function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
console.log(results);
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i], bounds);
}
map.fitBounds(bounds);
}
}
createMarker = function(place, bounds) {
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
});
// event listener to show the InfoWindow.
(function(marker, place) {
google.maps.event.addListener(marker, 'click', function() {
var content = '<h3>' + place.name + '</h3> ' + place.formatted_address + '<br>',
infowindow = new google.maps.InfoWindow({
content: ''
});
if (place.rating) {
content += '<p> <b>Rating</b>: ' + place.rating + '</p>';
}
if (place.types) {
content += '<p> <b>Tags</b>: ';
for (var j = 0, tag; tag = place.types[j]; j++) {
content += tag + ', '
}
content += '</p>';
}
infowindow.content = content;
infowindow.open(map, marker);
});
})(marker, place);
markers.push(marker);
bounds.extend(place.geometry.location);
}
}
google.maps.event.addDomListener(window, 'load', initialize);

Permanent Google Map Infowindow

I have a marker which has a dynamic position (i.e. updated periodically). When marker is clicked, an infowindow is shown but when marker position is updated, the infowindow gets automatically closed. I want that when marker position is updated, infowindow position should also get updated automatically. How to solve this.
P.S. :- infowindow contain a form which is editable by the user.
Problem : when user is editing/filling the form and marker position gets updated (form not submitted yet), then the form will get closed and user will lose his data.
<script type="text/javascript">
var map;
var lat_longs = new Array();
var geocoder = null;
var infoWindow = new google.maps.InfoWindow();
var trafficLayer = null;
var weatherLayer = null;
var markers = new Array();
var poi = new Array();
var fitMap = 0;
loc_array = new Array();
totUpdateOld = new Array();
ident = 0;
function showMap() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng('-0.57128','117.202148'),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
geocoder = new google.maps.Geocoder();
trafficLayer = new google.maps.TrafficLayer();
weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELCIUS
});
showCarPosition(function() {
fitMapToBounds();
});
}
function showCarPosition(){
if (markers.length>0){
ident = 2;
}
var car_icon;
jQuery.getJSON('<s:property value="jsonUrl"/>','', function(data) {
var arrayCar = data.listCar;
for (var i = 0; i < arrayCar.length; i++) {
var car = arrayCar[i];
var status = "";
var tanggal = "never";
var car_type = (car.type != "" || car.type != null)?' ('+car.type+')':'';
if(car.lastUpdate == null){
car_icon = ctx + 'web/img/car_black.png';
status = "Belum pernah kirim data";
}else if((not_active = (currentdate - stringToDate(car.lastUpdate))/ 1000 / 60) >= 30){ //diff in minute
car_icon = ctx + 'web/img/car_red.png';
status = convertMinute(not_active);
}else if((((currentdate - stringToDate(car.lastUpdate))/ 1000 / 60) >= 5) && (car.lastSpeed == 0)){ //diff in minute
car_icon = ctx + 'web/img/car_yellow.png';
status = "Berhenti";
}else
car_icon = ctx + 'web/img/car_green.png';
if(car.lastUpdate != null){
var splitDate = car.lastUpdate.split("T");
tanggal = splitDate[1]+" "+splitDate[0].split("-")[2]+"-"+bulan[parseInt(splitDate[0].split("-")[1])]+"-"+splitDate[0].split("-")[0];
}
var coordinate = new google.maps.LatLng(car.latitude, car.longitude);
var windowContent =[
'<div class="windowcontent"><ul class="nav infowindow nav-pills nav-stacked">',
'<li class="active">'+car.plate +car_type+' - '+ car.driverName +'</li>',
(status != null)?'<li>'+status+'</li>':'',
(car.phoneNumber != null)?'<li>Phone : ' + car.phoneNumber+ '</li>':'',
'<li>Last Temp : ' + car.lastTemp+ '</li>',
(parseInt(car.lastSpeed)>0)?'<li>Last Speed : ' + car.lastSpeed+ '</li>':'',
(car.type != "" || car.type != null)?'<li>Last Speed : ' + car.lastSpeed+ '</li>':'',
'<li>Last Connected : ' + tanggal+ '</li>',
'<li>'+((car.note != null)?car.note:'no notes')+'<li>',
'<div id="'+car.id+'"></div></ul>',
'<span id="'+car.id+'" onclick="editinfo(this, \''+car.note+'\');">Edit Note</span></div>']
.join('');
if (ident == 0){
var marker = createMarker({
map: map,
position: coordinate,
icon: car_icon,
labelContent: ((car.driverName == null)?car.plate:car.driverName)+'-'+car.lastSpeed,
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
});
loc_array[car.id] = i;
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
jQuery('.viewlog').click(function() {
jQuery.history.load(jQuery(this).attr('href'));
return false;
});
});
}else{
if (car.totalUpdate > totUpdateOld[car.id]) {
var map_post = loc_array[car.id];
markers[map_post].setMap(null);
var marker = updateMarker({
map: map,
position: coordinate,
icon: car_icon,
labelContent: ((car.driverName == null)?car.plate:car.driverName)+'-'+car.lastSpeed,
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
}, map_post);
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
jQuery('.viewlog').click(function() {
jQuery.history.load(jQuery(this).attr('href'));
return false;
});
});
}
}
totUpdateOld[car.id] = car.totalUpdate;
}
fitMapToBounds();
});
setTimeout("showCarPosition()",5000);
}
function createMarker(markerOptions) {
var marker = new MarkerWithLabel(markerOptions);
markers.push(marker);
lat_longs.push(marker.getPosition());
return marker;
}
function updateMarker(markerOptions,id) {
var marker = new MarkerWithLabel(markerOptions);
markers[id] = marker;
lat_longs[id] = marker.getPosition();
return marker;
}
function fitMapToBounds() {
var bounds = new google.maps.LatLngBounds();
if (fitMap == 0){
if (lat_longs.length>0) {
for (var i=0; i<lat_longs.length; i++) {
bounds.extend(lat_longs[i]);
}
map.fitBounds(bounds);
fitMap = 1;
}
}
}
function bindInfoWindow(marker, event, windowContent) {
google.maps.event.addListener(marker, event, function() {
infoWindow.setContent(windowContent);
infoWindow.open(map, marker);
});
}
jQuery(document).ready(function() {
showMap();
});
</script>
<div id="map_canvas" class="widgettitle" style="height:540px;"></div>
call this function when the marker position is changed .
infowindow.open(map,marker);
Put an onblur event handler on the text field that calls a halt to the repositioning.
Then when it is submitted and goes to the new point, restart it (if needed).

Dynamically populated google maps sidebar

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

Categories