I want to create a google map in which the markers I want to show are coming from database and the infowindow data comes from database as well which is different for each marker obviously. Code that I am using now is:
<script type="text/javascript">
var delay = 100;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(21.0000, 78.0000);
var mapOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status){
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {}
}
next();
});
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
<?php
global $wpdb;
$results = $wpdb->get_results("select * from $wpdb->postmeta where meta_value = 'Canada'");
$num_rows = $wpdb->num_rows;
?>
var locations = [
<?php foreach ($results as $doc_meta_data) {
echo "'";// . $doc_meta_data->meta_id;
echo get_post_meta($doc_meta_data->post_id, 'address', true).",";
echo get_post_meta($doc_meta_data->post_id, 'state', true).",";
echo get_post_meta($doc_meta_data->post_id, 'country', true);
echo "',";
}?>
];
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
How can I add make each markers info dynamic ie, it should come from the admin panel.
URL:http://intigateqatar.com/ozone/find-a-doc/
You need to create infowindow in createMarker() function in order infowindows to be unique for each marker:
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map
});
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
bounds.extend(marker.position);
}
The InfoWindow's on the linked page have dynamic content(currently the address), I guess you don't need the address as content.
Currently the locations-array has the following structure.
[address1,address2,address3,....]
Request the infos and create an array with this structure:
[[address1,info1],[address2,info2],[address3,info3],....]
Change geocodeAddress() into the following:
function geocodeAddress(details, next) {
//details[0] is the address, pass it as address-property to geocode
geocoder.geocode({address:details[0]}, function (results,status){
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
//details[1] is the info fetched from the DB,
//pass it as add-argument to createMarker()
createMarker(details[1],lat,lng);
}else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {}
}
next();
});
}
Note: echoing the single variables is not a good idea , a single-quote in either address(or the info) will result in a script-error(and there are more critical characters, e.g. linebreaks).
Populate a PHP-array with the values and use json_encode() to print the array.
Related
Stuck on the map marker bounce.I am showing a multiple location using marker on map dynamically. When i click on event button(Map icon), on map same location bounce.
Sharing my code:
Here is my view
What i want that, When i am clicking on map icon in Activity same marker on map with lat-long will bounce.Same for all.
Here is my a href link for map
<i class="fa fa-map-marker" aria-hidden="true"></i>
// here i gt latitude and longitude
Google map script:
<script>
function initMap() {
window.map = new google.maps.Map(document.getElementById('googleMap'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
<?php
if($listactivity !="" && count($listactivity)>0){
foreach($listactivity as $location){ ?>
var location = new google.maps.LatLng({{ $location->latitude }}, {{ $location->longitude }});
var marker = new google.maps.Marker({
position: location,
map: map
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
}));
<?php }} ?>
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function () {
if (map.getZoom() > 16) map.setZoom(16);
google.maps.event.removeListener(listener);
});
}
</script>
How can i do it dynamically.
This is how I do:
// Pushing all markers to an object with an ID, after the end of your php for loop, with the current loop variable, in this case use for cycle instead of foreach
<script>
var markers = [];
function initMap() {
window.map = new google.maps.Map(document.getElementById('googleMap'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
<?php
if($listactivity !="" && count($listactivity)>0){
for ($i = 0; $i < count($listactivity); $i++){ ?>
var currentIndex = {{ $i }}
var location = new google.maps.LatLng({{ $listactivity[$i]->latitude }}, {{ $listactivity[$i]->longitude }});
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push({id: currentIndex, marker: marker});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
}));
<?php }} ?>
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function () {
if (map.getZoom() > 16) map.setZoom(16);
google.maps.event.removeListener(listener);
});
}
// Setting up click event
$('.markericon').on('click', function () {
var markerId = $(this).attr('data-id');
var result = $.grep(markers, function (e) {
if (e.id == markerId) {
return e;
}
});
// Trigger marker click event, or bounce effect.
google.maps.event.trigger(result[0].marker, 'click');
});
</script>
// Adding a markericon class, and storing the location's marker id in a data attribute
// e.g <a href="#" class="markericon" data-id="1">
I have this code, which works fine, but there is just one issue which I am getting:
When we search nearby places, it appends the new nearby search markers with the old markers, screenshots are attached in these links.
Here I have searched the nearby banks:
http://prntscr.com/aouxra
It has successfully shown, but now if I search another nearby place like hotel, it will append its markers with the banks markers which has been searched previously, like this:
http://prntscr.com/aouz23
I want to only show the markers of the autocompleted nearby search query only.
function getNearby(lat,lng,map){
var availableTags = [
"hotel",
"bank",
"atm",
"school",
];
$( "#nearby" ).autocomplete({
source: availableTags,
select: function (event, ui) {
var request = null;
request = {
location: {lat:lat, lng:lng},
radius: 5500,
types: [ui.item.value]
};
var service = null;
var infowindow = null;
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
//var markers = [];
var markers = [];
var bounds = map.getBounds()
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++)
{
createMarker(results[i]);
//alert(results)
}
}
}
function createMarker(place) {
//markers.push(place);
var marker = '';
var placeLoc = '';
placeLoc = place.geometry.location;
marker = new google.maps.Marker({
map: map,
position: placeLoc
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
alert(markers.length);
}
});
}
function getLocation() {
$("#myNearby").css('display', 'block');
$("#directions").css('display', 'none');
$("#map").css('display', 'none');
$("#panel").css('display', 'none');
$("#load").css('display', 'none');
$("#googleMap").css('display', 'block');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
setLocationValue(position.coords.latitude,position.coords.longitude);
//getCurrentLocationValue(position.coords.latitude,position.coords.longitude);
var mapProp = {
center:new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
zoom:10,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var myMarker = new google.maps.Marker({
position: {lat:position.coords.latitude, lng:position.coords.longitude},
animation:google.maps.Animation.BOUNCE
});
myMarker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content:"You are Located in Lat: "+position.coords.latitude+' Lng: '+position.coords.longitude
});
infowindow.open(map,myMarker);
getNearby(position.coords.latitude,position.coords.longitude,map);
<?php /*?>$("#myNearby a").click(function(){
//alert('Working');
var request = {
location: {lat:position.coords.latitude, lng:position.coords.longitude},
radius: 5500,
types: [$("#location").val()]
};
infowindow = new google.maps.InfoWindow();
var 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
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
});<?php */?>
}
function setLocationValue(lat,lng){
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
//console.log(results);
$.each(arrAddress, function(i, address_component) {
if (address_component.types[0] == "locality") {
itemLocality = address_component.address_components[0].long_name;
//console.log("City: " + address_component.address_components[0].long_name + itemLocality);
$("#location").val(itemLocality);
}
});
}
else{
alert("No results found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
});
}
Remove the existing markers from the map before showing the new ones. Make the markers array global, then do this at the beginning of getNearby:
for (var i=0; i<markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
I have a page that a user inputs markers on a google map and it saves the center of map latitude and longitude, zoom and the latitude and longitude of the marker into MySQL. Next I'm trying to have a page that displays all the different maps a user has saved with the markers. I have searched and all I can find is how to display multiple markers on the same map or a set number of maps on the same page with a set lat and long.
Could anybody suggest where to start with this or a tutorial on this.
Here is the code I've started with that displays one google map with all the markers that have been entered. Not familiar with javascript, so need pointed in the right direction.
Thanks
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=&sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
var latitude= <?php echo json_encode($maplat);?>;
var longitude= <?php echo json_encode($maplon); ?>;
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(latitude, longitude),
zoom: <?php echo $mapzoom;?>,
mapTypeId: 'satellite'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var date = markers[i].getAttribute("date");
var log = markers[i].getAttribute("log");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latit")),
parseFloat(markers[i].getAttribute("longit")));
var html = "<b>" + date + "</b> <br/>" + log;
var marker = new google.maps.Marker({
map: map,
position: point,
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
I am not able to convert my coordinates to address ...
Almost got adjusting function below ... but how many markers are, just creating only the last marker ...:
My function to create markers:
function createMarker(point,info,map) {
var iconURL = 'img/pata.png';
var iconSize = new google.maps.Size(32,34);
var iconOrigin = new google.maps.Point(0,0);
var iconAnchor = new google.maps.Point(15,30);
var myIcon = new google.maps.MarkerImage(iconURL, iconSize, iconOrigin, iconAnchor);
var marker = new google.maps.Marker({
position : point,
html : info,
map : map,
icon: myIcon
});
var infowindow = new google.maps.InfoWindow({
content: "Dispositivo: " + info + "<br> Endereço: " + point
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,this);
});
}
My function to create bookmarks:
Function that was trying to adapt (just wanted to send the coordinates and he convert to address and leave the infowindow when clicking)
function codeLatLng() {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
could,
but do not know how to get the addresses separately to list ...
but got the click infowindow:
function createMarkerAtual(point,info,dt,map) {
var iconURL = 'img/dog2.png';
var iconSize = new google.maps.Size(45,45);
var iconOrigin = new google.maps.Point(0,0);
var iconAnchor = new google.maps.Point(15,30);
var myIcon = new google.maps.MarkerImage(iconURL, iconSize, iconOrigin, iconAnchor);
var marker = new google.maps.Marker({
position : point,
html : info,
map : map,
icon: myIcon
});
google.maps.event.addListener(marker, 'click', function() {
endereco(info,this.position);
infowindow.open(map,this);
});
}
function endereco(info,point){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': point}, function(results, status){
if (status == google.maps.GeocoderStatus.OK){
infowindow.setContent('<b>Coordenadas: </b>' + point + '<br><b>Dispositivo:</b> ' + info + '<br><b>Endereço: </b>' + results[0].formatted_address);
} else {
}
});
}
I have a gmap and I only want to display markers in the viewable area. I have added a listener to get the bounds of the map and call gather the markers within the bounds. the problem is that when i bounds change, i want to clear the map and reload with the updated markers. currently the map will just continue to reload the markers on top of each other which makes the map extremely slow. I have tried:
google.maps.event.addListener(map, 'bounds_changed', function () {
clearOverlays();
loadMapFromCurrentBounds(map);
});
And that will not load any markers at all. I have also tried:
function loadMapFromCurrentBounds(map) {
clearOverlays();
And this will not load any markers either. Below is the code that will load all markers and functions as i want it to with the exception of clearing the old markers when the bounds change.
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap'
});
google.maps.event.addListener(map, 'bounds_changed', function () {
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() {
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
}
}
function loadMapFromCurrentBounds(map) {
clearOverlays();
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
Please help... I have been beating my head against the computer all night researching and trying to figure this out. Feel free to email and/or ask for any questions.
You cant remove all markers, but it is possible to setMap to null on every visible marker.
I am doing it like that
add markers array to map object
add clearAllMarkers function to map object
every marker is added to the map is also added to markers array
clearAllMarkers function is something like that:
for (var idx=0;idx<=map.markers.length;idx++){
map.markers[idx].setMap(null);
}
I belive you are adding separate markers object to you're markers array. You're markers array should be full of markers references!!!
var map = []; //elrado's code
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap'
});
map.markers = [];//elrado's code (add narkers.array to map object)
google.maps.event.addListener(map, 'bounds_changed', function () {
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() {
if (map.markers) {
for (i in map.markers) { //Might be you'll need to use map.markers.length
markers[i].setMap(null);
}
map.markers = [];//reinit map.markers.array
}
}
function loadMapFromCurrentBounds(map) {
clearOverlays();
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
map.markers.push(marker);//elrado's code
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
I have to warn you that this was written from the head (no test), but something like that should work. Basicly you are setting setMap(null) on separate markers not on objects you're showing on the map.
Below is the complete code solution to the problem.. Thanks for your help.
var map; //elrado's code
var markersArray = []; //elrados's code create array for markers
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(33.553029,-112.054017),
zoom: 13,
mapTypeId: 'roadmap'
});
google.maps.event.addListener(map, 'tilesloaded', function () {
clearOverlays()
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() { //clear overlays function
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
function loadMapFromCurrentBounds(map) {
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
markersArray.push(marker); //eldorado's code Define the array to put markers in
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}