Apologies in advance as this may seem a little complicated.
I have a Google Map Marker Array that my markers get added to called markersArray.
The details that get stored per marker are latitude, longitude, title, description.
Using the code below, it runs when a marker is clicked on my map
google.maps.event.addListener(marker, 'click', function(mll) {
console.log(mll);
console.log(markersArray);
var html= "<div style='color:#000;background-color:#fff;padding:5px;width:150px;'><p></p></div>";
iw = new google.maps.InfoWindow({content:html});
iw.open(map,marker);
});
mll shows the log for the actual marker and markersArray just shows me the list of markers within the Array.
What I've noticed is that the data stored in markersArray is no being taken into the actual marker itself.
Is there a way of doing this?
If there isn't is there a way to use Javascript to find the title from the markersArray depending on the latLng values that you will see in the following image.
I screenshot what I receive when I run the Marker Click Function
Markers are added as follows using AngularJS:
$scope.createmarker = function () {
geocoder.geocode({
'address': selectedItem.gps
}, function (response, status) {
geocode_results = new Array();
geocode_results['status'] = status;
top_location = response[0];
var lat = Math.round(top_location.geometry.location.lat() * 1000000) / 1000000;
var lng = Math.round(top_location.geometry.location.lng() * 1000000) / 1000000;
geocode_results['lat'] = lat;
geocode_results['lng'] = lng;
geocode_results['l_type'] = top_location.geometry.location_type;
marker = new google.maps.Marker({
icon: mapIcon,
position: new google.maps.LatLng(lat, lng),
map: map,
title: selectedItem.title
});
markersArray.push(marker);
console.log(markersArray);
console.log(marker);
});
};
Using title instead of mll
google.maps.event.addListener(marker, 'click', function(title) {
console.log(mll);
console.log(markersArray);
var html= "<div style='color:#000;background-color:#fff;padding:5px;width:150px;'><p></p></div>";
iw = new google.maps.InfoWindow({content:html});
iw.open(map,marker);
});
Related
I receive json data from a server and need to add them to a google map. It works fine, however, I only see one marker and I assume every time I add a marker it changes it to new coordinates and doesnt add an extra marker. How can I define markers as an array?
$.getJSON(url, function(data) {
var entry = data.feed.entry;
$(entry).each(function(){
for (var prop in this["gsx$instruments"]) {
//alert(this["gsx$instruments"][prop]);
listContacts(this["gsx$instruments"][prop])
var myLatLng = {lat: Number(this["gsx$ycor"][prop]), lng: Number(this["gsx$xcor"][prop])};
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: this["gsx$instruments"][prop]
});
}
// Column names are name, age, etc.
//$('.results').prepend('<h2>'+this.gsx$instruments.$t+'</h2><p>'+this.gsx$type.$t+'</p>');
});
});
Add a new function addMarker and use that function to include markers also keep the map variable outside the ajax call as well. updated code below
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: {lat: LAT, lng: LONG}
});
function addMarker(position, map, title){
var marker = new google.maps.Marker({
position: position,
map: map,
title: title
});
}
$.getJSON(url, function(data) {
var entry = data.feed.entry;
$(entry).each(function(){
for (var prop in this["gsx$instruments"]) {
//alert(this["gsx$instruments"][prop]);
listContacts(this["gsx$instruments"][prop])
var myLatLng = {lat: Number(this["gsx$ycor"][prop]), lng: Number(this["gsx$xcor"][prop])};
addMarker(myLatLng,map,this["gsx$instruments"][prop]);
}
// Column names are name, age, etc.
//$('.results').prepend('<h2>'+this.gsx$instruments.$t+'</h2><p>'+this.gsx$type.$t+'</p>');
});
});
Essentially, you first need to add the markers to an array of markers
Suppose you have JSON providing the markers and supposing each marker has a name and coordinates attributes
function formatMarkers (){
// Loop through all of the JSON entries provided in the response
for (var i = 0; i < markersArray.length; i++) {
var markers = markersArray[i];
// Create popup windows for each record
var contentString = '<p><b>Name</b>: ' + markers.name + '</p>';
// Converts each of the JSON records into Google Maps Location format
formattedMarkers.push({
latlon: new google.maps.LatLng( markers.coordinates[1], markers.coordinates[0] ),
message: new google.maps.InfoWindow({
content: contentString,
maxWidth: 320
}),
username: markers.name
});
}
return formattedMarkers;
}
Then you need to render each of them
formattedMarkers.forEach(function (n) {
var marker = new google.maps.Marker({
position: n.latlon,
map: map,
icon: icon
});
// For each marker created, add a listener that checks for clicks
google.maps.event.addListener(marker, 'click', function () {
// When clicked, open the selected marker's message
n.message.open(map, marker);
});
marker.setMap(map);
}
I hope I've been helpful.
I have recently started working on google maps API V3 and right now I am stucked in a problem.
I have two markers plotted on my map. What I want is that on moving the mouse cursor on map, it continuously checks for latitude and when the latitude is equal to that of the marker present on map it should show an alert message.
The problem which I am facing is that it is working only for one marker, not for all markers present on map
Here is my code:
$.ajax({
type: "GET",
url: $('meta[name="_home_url"]').attr('content') + '/walkalong/' + position.coords.latitude + "/" + position.coords.longitude,
success: function (response) {
// Looping through all the entries from the JSON data
for (var i = 0; i < response.data.shops.length; i++) {
// Current object
var obj = response.data.shops[i];
// Sets the map marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(obj.latitude, obj.longitude),
map: map,
info: contentString,
optimized: false,
icon: pinIcon,
id: obj.shop_id,
animation: google.maps.Animation.DROP,
title: obj.title // this works, giving the marker a title with the correct title
});
google.maps.event.addListener(map, 'mousemove', function (event) {
Latfetch = event.latLng.lat().toFixed(4);
Longfetch = event.latLng.lng().toFixed(4);
if (Latfetch === obj.latitude) {
alert(obj.latitude);
}
});
and the JSON response is:
{"status":200,"data":{"shops":[{"shop_id":7,"name":"reebok","logo":"543813f8-cc75-4217-a3d4-bb08992f66af.png","latitude":"17.4539","longitude":"78.3902","shop_description":"","opening_time":"09:00:00","closing_time":"18:00:00","mobile":"4567896545","address_line1":"ameerpet","city":"Dispur","state":"Arunachal Pradesh","country":"India","pincode":"435645","baazar_area":"","front_image":"6c08a359-fb7f-4e09-af25-3c2d43a32327.jpg","distance":0.703},{"shop_id":9,"name":"ahex","logo":"86c6f7f8-625c-4a7a-aee4-10f7d16f1f12.jpg","latitude":"17.4519","longitude":"78.3879","shop_description":"","opening_time":"09:00:00","closing_time":"18:00:00","mobile":"4233488384","address_line1":"madhapur","city":"Panaji","state":"Goa","country":"India","pincode":"345678","baazar_area":"","front_image":"31e96273-c360-4b49-87d1-418bdac26dc3.jpg","distance":0.711}],"shopImages":[{"logo":"543813f8-cc75-4217-a3d4-bb08992f66af.png","front_image":"6c08a359-fb7f-4e09-af25-3c2d43a32327.jpg","internal_image":"e988011f-f2c1-4b08-8582-0f36e85dc4f9.jpg","rack_image":"rack.jpeg","product_image":"item.jpeg"}]}}
Anyone there who could help?
I can only guess it just works only for one because you can only add one listener for mousemove. You could add the event on the marker instead:
for (var i = 0; i < response.data.shops.length; i++) {
...
var marker = new google.maps.Marker({
...
});
marker.addListener('mousemove', function(event) {
var latfetch = event.latLng.lat().toFixed(4);
var longfetch = event.latLng.lng().toFixed(4);
var lat = this.position.lat();
if(latfetch === lat){
alert(lat);
}
});
}
I have been playing around with the twitter API getting random tweets or even geo tagged tweets and also with the google maps API. However I want to combine this two and try and show geo tagged tweets on a google map. Here is my code for getting the geo tagged Tweets which work fine.
var geo = (geo.coordinates[0], geo.coordinates[1])
//var geo = (34.052234, -118.243685)
client.get('search/tweets', { q:string.teamname, geocode: geo, count: 5},
function searchTweets(err, data, response) {
for(var index in data.statuses){
var tweet = data.statuses[index];
console.log(tweet.text);
console.log(tweet.geo.coordinates)
}
});
On a different file, I generated a map based on Longitude and Latitude, and I had the understanding that once I had retrieved the coordinates for the tweets, I could represent the tweets on a Google Map in the same way. However, my code is not working. My question is, how would I combine both pieces of code to generate a map which is marked with geo located Tweets?
function initialize() {
var myLatlng = new google.maps.LatLng(geo.coordinates[0], geo.coordinates[1]);
var mapOptions = {
center: myLatlng
zoom: 10,
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Tweet});
var infowindow = new google.maps.InfoWindow({
content: 'Geo tagged Tweet',
maxWidth:200 });
infowindow.open(map,marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker); });
}
google.maps.event.addDomListener(window, 'load', initialize);
I would do something like this (untested - I'm just writing down some thoughts).
1) You should strip down init so that it just contains the map set up. Ensure map is declared outside of the function, and include a call to the function that fetches your data using the lat/lng data.
var map;
function initialize() {
var lat = geo.coordinates[0];
var lng = geo.coordinates[1]
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = { center: myLatlng, zoom: 10 }
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
getData(lat, lng, processData);
}
2) You wrap your data fetching code in a new function declaration, which accepts lat/lng data, and a callback.
function getData(lat, lng, callback) {
client.get('search/tweets', { q:string.teamname, geocode: geo, count: 5},
function searchTweets(err, data, response) {
callback(data.statuses);
}
)
};
3) Process the tweet information. For each tweet create a marker (add the marker to an array of markers) and update the map
function processData(data) {
var markers = [];
for (var i = 0, l = data.length; i < l; i++) {
var marker = new google.maps.Marker({
id: i,
position: myLatlng(data[i].geo.coordinates[0], data[i].geo.coordinates[1),
map: map,
title: "Tweet"
});
markers.push(marker);
var infowindow = new google.maps.InfoWindow({
content: data[i].text,
maxWidth: 200
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}
I'm trying to make a simple page that allows addresses from a mysql database to be converted to lat and long and then displayed as markers on a map.
Most of the code below comes from the google docs with the addition of some geocoder stuff.
I can successfully alert the correct coordinates (see line 48-53) but then I try to pass them into 'point' variable for google maps to create a marker but nothing appears on the map.
Can anyone see whats wrong with my code? I'm not familiar with Javascript so it could be something really fundamentally wrong.
Thanks
function load() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 3,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml3.php", function(data) {
var coords;
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 type = markers[i].getAttribute("type");
geocoder.geocode( { 'address': address}, function(results, status) {
var latpoint = parseFloat(results[0].geometry.location.lat());
var lngpoint = parseFloat(results[0].geometry.location.lng());
coords = latpoint + ', ' + lngpoint;
//alert(coords); //For Testing
});
var point = new google.maps.LatLng(coords);
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
The LatLng object constructor is waiting for Number type. Here you give it a string with the concatened coordinates, wich is wrong.
Look at the doc here.
Try that instead :
var latpoint = parseFloat(results[0].geometry.location.lat());
var lngpoint = parseFloat(results[0].geometry.location.lng());
var point = new google.maps.LatLng(latpoint, lngpoint);
And please refer to the #Pekka 웃 comment to be sure people answer you next time.
I am using google map which shows marker with information window...in which i display address but i want to show the name as well in information window when a marker is clicked. Any help will be highly appreciated.
function load()
{
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(-37.816667,144.966667), 10);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var geocoder = new GClientGeocoder();
GDownloadUrl("shops.xml", function(data) {
var xml = GXml.parse(data);
shop = xml.documentElement.getElementsByTagName("shop");
for (var i = 0; i < shop.length; i++) {
var name= shop[i].getElementsByTagName("name");
name = name[0].childNodes[0].nodeValue;
var address= shop[i].getElementsByTagName("address");
address = address[0].childNodes[0].nodeValue;
geocoder.getLocations(address, addToMap);}
}); }
function addToMap(response)
{
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
function createMarker(point,address)
{
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function()
{
map.openInfoWindowHtml(point, address);
});
return marker;
}
map.addOverlay(createMarker(point, response.name));
}
Use API v3 and in your marker setup set the tite of the marker to "name" then after adding the click listener you will be able to refer to the title of the clicked marker - if that is what you wanted.
//get your point and name whatever way you plan to do it
...
function createMarker(point,name){
var marker = new google.maps.Marker({
position: point,
map: map,
title: name,
}) ;
var content='Whatever info you want plus'+name;
var infowindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
return marker;
}
Please check the closures as I wrote it just now.
K