How to dynamically add data to google maps API? - google-maps-api-3

I have got a map that I want to have a feed of lat/long data getting pushed to the map data array. I have the function to get the data, but am having trouble getting that to be usable in the map data array.
The idea is to have a new marker drop in when a new coordinate is added to the array. Any ideas? Thanks in advance!
var ID='0';
var DATA=[];
function getData(){
var url = 'http://us7.fieldagent.net/api/newResponses/';
//url = 'http://us7.fieldagent.net/api/newResponses/;
$.post(url,{'id':ID},function(data){
if(data.status_id == 0){
ID = data.id;
console.log('Last Id: '+data.id);
var new_data = data.responses;
var count = 0
$.each(new_data,function(i,v){
count += 1;
var coord = 'new google.maps.LatLng('+v.lat+','+v.lon+'),';
DATA.push(coord);
})
console.log('Added '+count+' responses..')
}
});
}
$(document).ready(function(){
getData();
setInterval(getData,20*1000);
});
function drop() {
for (var i = 0; i < DATA.length; i++) {
setTimeout(function() {
addMarker();
}, i * 500);
}
}
function addMarker(){
markers.push(new google.maps.Marker({
position: DATA[iterator],
map: map,
draggable: false,
icon: 'fatie.svg',
animation: google.maps.Animation.DROP
}));
iterator++;
}

You need to actually add the item to the map. Right now, you're only adding an item to your DATA array. You need to call addMarker with the new data as well.
You seem to want to add these markers to the map at an interval so they drop onto the map over time, while also being able to query for new markers from your server.
Try code like this:
var ID='0';
var DATA=[];
function getData(){
var url = 'http://us7.fieldagent.net/api/newResponses/';
$.post(url,{'id':ID},function(data){
if(data.status_id == 0){
ID = data.id;
console.log('Last Id: '+data.id);
var new_data = data.responses;
var count = 0
$.each(new_data,function(i,v){
count += 1;
var coord = 'new google.maps.LatLng('+v.lat+','+v.lon+'),';
DATA.push(coord);
});
console.log('Added '+count+' responses..');
if (count > 0) addMarker(); //call addMarker if there are new markers
}
});
}
$(document).ready(function(){
getData();
setInterval(getData,20*1000);
});
function addMarker(){
if (DATA.length == 0) return; //exit if DATA is empty
markers.push(new google.maps.Marker({
position: DATA.shift(), //take the first item in DATA
map: map,
draggable: false,
icon: 'fatie.svg',
animation: google.maps.Animation.DROP
}));
if (DATA.length > 0) setTimeout(addMarker, 500); //call again if needed
}

Create a Method which does two things.
Add to the Array
Add the Item to the map

Related

Delete a layer in Openlayers

I added a markers by adding layer in OpenLayers.
I use it in my asp project and I load a map and I can add multi icons.
Now I load my locations and show them by that icons.
My code is like this:
for (var i = 0; i < loc.length; i++) {
LocationArray.push(loc[i]);
iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat(loc[i])),
name: 'Null Island',
population: 4000,
rainfall: 500
});
iconFeatures.pop();
debugger
iconFeatures.push(iconFeature);
vectorSource = new ol.source.Vector({
features: iconFeatures //add an array of features
});
iconStyle = new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 100],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.8,
src: '/images/icon.png',
}))
});
vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: iconStyle
});
map.addLayer(vectorLayer);
}
Now I want to Delete this layer when I click on it.
I can detect where is it clicked and I response it but I don't know how I can delete it.
My code is like this:
map.on('click', function (evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
if (feature) {
var coordinates = feature.getGeometry().getCoordinates();
if (confirm("Do you want to delete?")) {
// What should I code here?
}
} else {
// .....
}
});
The forEachFeatureAtPixel callback can also receive the layer, if you save that it is easy to remove the layer:
map.on('click', function (evt) {
var vectorLayer;
var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
vectorLayer = layer;
return feature;
});
if (feature) {
var coordinates = feature.getGeometry().getCoordinates();
if (confirm("Do you want to delete?")) {
map.removeLayer(vectorLayer);
}
} else {
// .....
}
});
If you want to keep the layer but remove the markers you can use the clear() method.
vectorLayer.getSource().clear();
Thanks for response
I've found it by map.removeLayer(layer); code

Google Map: Link to the map according to feature type

I have a google Map with markers on a webpage.
Each marker has a unique feature position and type
This is the scenario I would like to put in place:
On another webpage I have static links to different markers of the map.
If you click on one of those links, you are directed to the map in which, one of these markers is centered (and its info window open).
But the markers latitude and longitude might change while the links will never change.
This means, I need the links not to use latitude and longitude info but markers feature type instead (which are remain the same).
How can I do that?
Here is my sample google Map script so far:
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 48.85639, lng: 2.33625}, // default centering
zoom: 18,
styles:
[
{featureType: 'poi',stylers: [{ visibility: 'off' }]},
{featureType: 'transit.station',stylers: [{ visibility: "off" }]}
]
});
var features = [
{position: new google.maps.LatLng(48.85659, 2.33555),type: 'markerone'},
{position: new google.maps.LatLng(48.85619, 2.33695),type: 'markertwo'}
];
var icons = {
'markerone': {icon: 'icon_one.png'},
'markertwo': {icon: 'icon_two.png'}
};
var contents= {
'markerone': {text: 'Content 1'},
'markertwo': {text: 'Content 2'}
};
for (var i = 0, feature; feature = features[i]; i++)
{
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
var content = contents[feature.type].text;
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker,'mouseover', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
google.maps.event.addListener(marker,'mouseout', (function(marker,content,infowindow){
return function() {
infowindow.close(map,marker);
};
})(marker,content,infowindow));
}
}
</script>
In this sample, I have to markers.
One has a feature type of "markerone" and the second is "markertwo".
How can I set my links to redirect and center the map around a specific marker in this kind of fashion:
http://www.mywebsite.com/mymap.php?myvariable=markertwo
Thank you.
First you would have to get the parameters. The example below gets all parameters and put them into an array. There you can search for your certain paramater like "markerType" and check if it's given or not. If not you have to perform a default action, otherwise you can handle the certain markerType like finding the correct marker, setting the map center to it and open the corrosponding infoWindow.
You just have to call the focusMarkerType-method onload of your page.
function getSearchParameters() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
function focusMarkerType(){
var params = getSearchParameters();
if(params.markerType!=null){
//Handling the certain marker type
var found = false;
for (var i = 0, feature; feature = features[i]; i++) {
if (feature.type == params.markerType) {
found = true;
map.setCenter(feature.position);
//more...
break;
}
}
if (!found) {
console.log("unknown type")
}
}else{
//Handling default behaviour if no marker type is given
}
}

Can't get Google Maps api v3 to display markers from xml file

I should have on my hands what is proper working JS and an xml file...I'm simply trying to take advantage of the huge database of locations that has been offered up as free for everyone to use - located # http://www.craftbeer.com/breweries/brewery-locator/find-a-us-brewery
I'm tried using their maps.js and xml file...but all I end up with is a blank maps screen...
Here is the Javascript...
/*********************************************
**Google Maps Custom API work**
This code can be reused on any site to display a local map of breweries from our local iMis dump, as well as pull in beermapping.
Hey! Don't forget to include API in functions.php! Function is conditionally initialized in footer.php
*/
//Set up variables to create marker
var gmarkers = [];
var mapMarkers = [];
var geocoder = new google.maps.Geocoder();
var icon = 'http://www.craftbeer.com/wp-content/uploads/marker.png';
//Initialize Map
function view_map(xml_file, latitude, longitude, varZoom) {
console.log('view map');
map = new google.maps.Map(document.getElementById("map_canvas"), { //Create the map, Set Default Zoom level and type
center: new google.maps.LatLng(latitude, longitude),
zoom: varZoom,
mapTypeId: 'roadmap',
panControl: true,
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: false,
overviewMapControl: false
});
//-- Listeners --//
google.maps.event.addListener(map, 'center_changed', function() {
console.log('center changed');
//clearMarkers();
});
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
//this part runs when the mapobject is created and rendered
console.log("loaded");
$("#loading-screen").fadeOut(250, function(){});
$("#loading-icon").fadeOut();
//google.maps.event.addListenerOnce(map, 'tilesloaded', function(){ });
});
//console.log(xml_file);
var download_file = xml_file; //this variable is passed in so we can re-use this script
//Pull in the XML feed
downloadUrl(download_file, function(data) {
console.log("downloading xml");
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//Loop through all markers in the XML file
for (var i = 0; i < markers.length; i++) {
var state = markers[i].getAttribute("state");
var x = markers[i].getAttribute("lat");
var y = markers[i].getAttribute("lng");
if ( state != 'PR' && state != 'VI' && state != 'GU' && x != "" ){
//console.log(state);
var ids = parseFloat(markers[i].getAttribute("id"));
var z = new google.maps.LatLng(x,y,i);
//console.log(x);
var _id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("company");
var address = markers[i].getAttribute("address");
var city = markers[i].getAttribute("city");
var zip = markers[i].getAttribute("zip");
var phone = markers[i].getAttribute("phone");
var url = markers[i].getAttribute("url");
var brewery_type = markers[i].getAttribute("type");
var member_type = '';
var member_type = markers[i].getAttribute("member_type");
var offer = markers[i].getAttribute("offer");
var html = "<div class='bubble_content'><strong>" + name + "</strong><br />";
html += address + "<br/>" + city + ", " + state + " " + zip;
if(url) html += "<br /><br /><a href='http://" + url + "' target='_blank'>Visit Web Site</a></div>";
//var marker = createMarker(ids, z, title, contentstring);
var marker = new google.maps.Marker({
position: z,
map: map,
title: name,
icon: icon,
html: html,
zindex: i
});
//Add a listener for every icon click
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,this);
//map.setZoom(10);
//map.setCenter(this.getPosition());
console.log(this);
});
gmarkers[ids] = marker;
mapMarkers.push(marker);
if( x && y ){
//console.log(ids);
var infowindow = new google.maps.InfoWindow({content: html});
}
/* google.maps.event.addListener(marker, 'click', function() {
console.log('marker clicked');
});
*/
//bounds.extend(z);
//map.fitBounds(bounds);
}//end check for US states only!
} //end for loop
var mcOptions = {gridSize: 60, maxZoom: 9};
var markerCluster = new MarkerClusterer(map, mapMarkers, mcOptions); //this is the function that groups the icons into markers
});
} //End full function to create map
/*
* FUNCTION
*
* click to bring up one icon when clicked from the list.
*/
function myclick(i){
console.log('clicked a title ' + i);
smoothScroll("#primary");
var lat = parseFloat(gmarkers[i].position.k);
var lng = parseFloat(gmarkers[i].position.B);
console.log(lat);
map.setCenter({lat: lat, lng: lng});
map.setZoom(13);
google.maps.event.trigger(gmarkers[i], 'click');
};
function createMarker(ids, z, title, contentstring){
console.log('createMarker');
var marker = new google.maps.Marker({
position: z,
map: map,
title: title,
html: contentstring,
icon: 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,marker);
});
gmarkers[ids] = marker;
//console.log(gmarkers[ids]);
};
/*
* FUNCTION findAddress()
*
* given an adress string, zoom the map to the proper state
*/
function findAddress(position) {
//Let's determind if we have a state (address) or LatLng
var addressStr = $("#state_select li.active").data('state-id');
if (addressStr != 'Select a State') address = "US State of "+addressStr;
if(position) {
var lat = parseFloat(position['latitude']);
var lng = parseFloat(position['longitude']);
var latlng = new google.maps.LatLng(lat, lng);
//console.log(latlng);
}
//Now let's geocode - two different cases
if (geocoder && position) { //If LatLng
//console.log('near me');
geocoder.geocode( { 'location': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(13);
}
} else {
alert("No results found");
}
}
});
} else if (geocoder && address!="") { //If State
//console.log('by state');
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(6);
}
} else {
alert("No results found");
}
}
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
}
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() {}
And here is the link to the xml file....
http://www.straighttothepint.com/wp-content/uploads/wp-google-maps/Google_Map_APIs.xml
I've spent days doing google searches and testing different sections of code to at least get a basic google map to show up via the xml file markers...but to no avail - Any help would be tremendously appreciated!!
~Cheers
EDIT:
Everything worked as expected once I included the following script inline on the page prior to calling the maps.js file. Thanks everyone!
<script>
$(document).ready(function(){
var latitude = 39.300299;
var longitude = -97.382812;
view_map('./uploads/your_xml_file.xml', latitude,longitude,4);
//scripts to handle mapping are in js/mylibs/map.js.php
});
</script>
Looking at the html and the code you provided above I constructed a fiddle for you:
http://jsfiddle.net/loanburger/qafsex5x/
I added two markers in an xml string at the top in the fiddle.
I basically parse the xml doing this:
var markers = $(xml).find("marker");
Its then simply the same for loop you had:
for (var i = 0; i < markers.length; i++)
{
...
}
The fiddle will show you the markers.

Google Maps API V3: pass marker coordinate to google directions service request

Users search my map with the Google places API which adds markers to my map. I have a click event inside each markers infowindow to get directions to that marker.
How do I pass the coordinates of the selected marker to my google directions service request?
So far I declared var placeLoc = null; as a global variable. I defined placeLoc=place.geometry.location; inside my create marker function. Then I have:
function calcRoute() {
var start = myLatLng;
var end = placeLoc;
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.BICYCLING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
The function renders directions to the wrong marker. I am guessing that it is just giving directions to the first marker in the array returned after the search and not the actual marker I selected. How do I provide the directions request the coordinates of a selected marker?
Below is the code that places the search results into the place variable:
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
// alert("getPlaces returns "+places.length+" places");
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
gmarkers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var place = places[i];
createMarker(place);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
// if (markers.length == 1) map.setZoom(17);
});
Something like this?
function createMarker(options) {
var marker = new google.maps.Marker(options);
google.maps.event.addListener(marker, 'click', function() {
placeLoc = marker.getPosition();
calcRoute();
});
return marker;
}

duplicated markers when calling a function using setinterval google maps v3

I have the next code to retrieve some data from a xml file. The problem is that when I want to refresh the markers, the response that I get is a duplicated marker in the map. How can I update the points without having duplicated markers?
Best regards
//<![CDATA[
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
// global "map" variable
var map = null;
var markerclusterer = null;
// A function to create the marker and set up the event window function
function createMarker(latlng, imei, html, estado, alias, speed, timestamp) {
if(estado == 1)
image = '/artworks/icons/truck_green3.png';
else
image = '/artworks/icons/truck_red.png';
var textoLabel= "this is the text"
var contentString = html;
var marker = new MarkerWithLabel({
position: latlng,
icon: image,
// map: map,
labelContent: textoLabel,
labelAnchor: new google.maps.Point(40, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.50},
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + imei + '<\/a><br>';
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
// create the map
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(37.169619,-3.756981),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
function getMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
downloadUrl("vehiculos.asp", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var imei = markers[i].getAttribute("imei");
var alias = markers[i].getAttribute("alias");
var speed= markers[i].getAttribute("speed");
var timestamp= markers[i].getAttribute("timestamp");
var estado= markers[i].getAttribute("estado");
var conectado= markers[i].getAttribute("conectado");
var html="<b>"+alias+"</b><br> a una velocidad de "+speed+" km/h <br/> ultima posicion a las: "+timestamp;
// create the marker
var marker = createMarker(point,alias+" "+imei,html,estado, speed, timestamp );
}
markerCluster = new MarkerClusterer(map, gmarkers);
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// Removes the overlays from the map, but keeps them in the array.
function clearOverlays() {
getMarkers(null);
}
// Deletes all markers in the array by removing references to them.
function deleteOverlays() {
clearOverlays();
getMarkers = [];
}
setInterval(clearOverlays, 3000);
setInterval(deleteOverlays, 4000);
setInterval(getMarkers, 5000);
Give your markers unique ids (maybe one of your existing attributes is already unique). If the unique id already exists, move that marker to the new location (or just don't add it again),if it doesn't, create a new marker.
If they don't move, you can also avoid duplicates by checking the distance between new markers and all your existing markers, if it is less than a "same marker" threshold (say ~0.1 meters), don't add it again.
There is a problem with your clearOverlays method (getMarkers(null) just calls getMarkers):
// Removes the overlays from the map, but keeps them in the array.
function clearOverlays() {
for (var i=0; i<gmarkers.length; i++)
{
gmarkers[i].setMap(null);
}
}

Resources