My array from a PHP file looks like this:
[
{"lat":"4.174475","lon":"73.509564","datetime":"2012-11-23 16:41:40"},
{"lat":"5.17","lon":"73.50633754680894","datetime":"2012-11-23 05:00:00"},
{"lat":"6.17","lon":"73.50633754680894","datetime":"2012-11-01 00:00:00"}
]
When I click the link #Three, it should generate 3 markers using the threeClick() function. Here is the function.
function threeClick () {
$.getJSON('json.search.php?idcard=<?php echo $idcardno; ?>&limit=3', function(data) {
var location;
$.each(data, function (key, val) {
addMarker(val.lat,val.lon);
});
}
The add marker function is like this (from: Plotting LatLng coordinates from Json Array on Google Map --- the markers all stack up in the same location)
function addMarker(lat,lng) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
icon: "images/mapIcons/red-dot.png"
});
markersArray.push(marker);
}
I generated the map using:
var map;
var markersArray = [];
function initMap() {
var latlng = new google.maps.LatLng(4.174475, 73.509564);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
}
Can anybody suggest me how I can show the markers on click of a link? What is wrong with this code?
You said you used this:
<a id="Three" onclick="threeClick">three</a>
The problem is that threeClick by itself doesn't actually call the function. It just references it. You need parenthesis to call it, like this:
<a id="Three" onclick="threeClick()">three</a>
But it would be even better to use jQuery to attach the handler. So set your html like this:
<a id="Three" href="#">three</a>
And then add this to your javascript:
$('#Three').click(function() {
threeClick();
return false;
});
Note that the return false here is to prevent the '#' click default action (setting the url hash) from happening.
Related
How do I add a user-input marker to Google Maps widget on my website, and get the latitude and longitude data from it?
Right now I am building an application which has to allow users to drop a marker to any location so that I can get that data and process it.
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(2.8,-187.3),
mapTypeId: 'terrain'
});
// Create a <script> tag and set the USGS URL as the source.
var script = document.createElement('script');
// This example uses a local copy of the GeoJSON stored at
// http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
document.getElementsByTagName('head')[0].appendChild(script);
}
// Loop through the results array and place a marker for each
// set of coordinates.
window.eqfeed_callback = function(results) {
for (var i = 0; i < results.features.length; i++) {
var coords = results.features[i].geometry.coordinates;
var latLng = new google.maps.LatLng(coords[1],coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
}
</script>
Right now I am using this, but this doesn't offer any user submitted markers.
Try running this working jsfiddle for demonstration and guidance on how users can place markers on a Google map. Note that it's based off of Google's example on adding and removing markers.
Full JS code below:
var map;
var markers = [];
function initMap() {
var haightAshbury = {
lat: 37.769,
lng: -122.446
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: haightAshbury,
mapTypeId: 'terrain'
});
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
addMarker(event.latLng);
});
// Adds a marker at the center of the map.
addMarker(haightAshbury);
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
You can get the marker's coordinates from the map's click event listener, e.g.:
map.addListener('click', function(event) {
console.log(event.latLng.lat());
console.log(event.latLng.lng());
addMarker(event.latLng);
});
Or from the addMarker method:
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
console.log(marker.getPosition().lat());
console.log(marker.getPosition().lng());
markers.push(marker);
}
Hope this helps!
I'm trying to send a few longitude and latitude variables to a function that will then generate a Google Map.
Starting with a datatable that retrieves various information stored in a database, I'm using data-attributes to store the lng and lat for each record. When a record is selected, a modal opens and the map is displayed.
I was able to get the map to display with default lng and lat points. But now I need to create a new map every time a record is selected.
Starting with the onclick event that triggers the modal to open (shortened as much as possible):
$('#example1').on('click', 'tr > td > a.actionMatch', function(e)
{
e.preventDefault();
var actimpbill = $(this).attr('data-actimpbill'); // random record info
var actramplat = parseFloat($(this).attr('data-actramplat')); // first lat
var actramplng = parseFloat($(this).attr('data-actramplng')); // first lng
var actdellat = parseFloat($(this).attr('data-actdellat')); // second lat
var actdellng = parseFloat($(this).attr('data-actdellng')); // second lng
// my map was opening in a grey box. this next piece of code fixed that
$("#actionMatchbackModal").on("shown.bs.modal", function () {
google.maps.event.trigger(map, "resize");
});
initMap(actramplat, actramplng, actdellat, actdellng); // my attempt to call a function and the variables to it
$('#actionMatchbackModal').modal('show'); // show the modal
});
Here is the function that sets the map. This is located outside of the initial onclick event that opens the modal (I'm not sure if that's a problem). This is where I'm trying to pass the variables that I created inside the onclick event:
function initMap(actramplat, actramplng, actdellat, actdellng)
{
// map options
var options = {
zoom: 8,
center: {actramplat, actramplng}
}
// new map
var map = new google.maps.Map(document.getElementById('map'), options);
// add marker
var marker = new google.maps.Marker({
position:{actdellat, actdellng},
map: map
});
}
I am probably butchering the function call. The function once housed the default lat and lng numbers and I was able to properly generate a map.
Edit
I just checked the console, and I am getting these errors:
InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number
InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
Edit
I just added parseFloat to the variables to ensure they are not strings, but still no success.
Edit
Here is what the data-attributes look like:
<a href="#" class="actionMatch" id="actionMatch"
data-toggle="modal" data-actimpbill="xxxxxxxx"
data-actramplat="39.11" data-actramplng="-94.63"
data-actdellat="39.03" data-actdellng="-96.83"
data-actreclat="39.84" data-actreclng="-96.65"
rel="tooltip" data-placement="right" title="Action Matchback"></a>
You can see the actramplat, actramplng, actdellat, actdellng in the A tag above.
Looking at their API, they expect lat/long values to be provided as an object literal that looks like this: var myLatLng = {lat: -25.363, lng: 131.044};
So you need to call it like this:
// map options
var options = {
zoom: 8,
center: {lat: dellat, lng: dellng}
}
// new map
var map = new google.maps.Map(document.getElementById('map'), options);
// add marker
var marker = new google.maps.Marker({
position:{lat: reclat, lng: reclng},
map: map
});
I'm trying to change GoogleMap marker icon by clicking div and using jquery. But it doesn't seem to be working, marker icon doesn't change. I assigned a variable that contains image path, but the thing is that if jquery changes it, it stays inside jquery function and is not passed back to global value.
Here is my code:
JS part
$(document).ready(function() {
$('#hurricanes').click(function (e){
iconic=jQuery(this).attr('hurr.png');
initMap();
});
$('#earthquakes').click(function (e){
iconic=jQuery(this).attr('durr.png');
initMap();
});
});
var iconBase = 'img/';
var iconic;
function createMarker(latlng, name, address1, address2, postalCode) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: name,
icon: iconBase + iconic
});
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -0.397,
lng: 10.644
},
zoom: 2,
mapTypeId: google.maps.MapTypeId.TERRAIN,
disableDefaultUI: true
});
displayMarkers();
}
And HTML buttons:
<div id="hurricanes" class="choices">HURRICANES</div>
<div id="earthquakes" class="choices">EARTHQUAKES</div>
you should reinitialize the map using JavaScript after you changed the marker. Have a look in the API Reference for all the options: https://developers.google.com/maps/documentation/javascript/3.exp/reference
Although I am not quite sure what you are exactly going to do, you can also remove the markers in specific coordinates and then add the new ones with new marker icons.
I found the solution by reinitializing both functions:
$(document).ready(function() {
$('#hurricanes').click(function (e){
iconic='hurr.png';
createMarker();
initMap();
console.log(iconic);
});
$('#earthquakes').click(function (e){
iconic='durr.png';
createMarker();
initMap();
console.log(iconic);
});
});
I am trying to create a website that has a google map in one column and in the second is a list of items with location elements. On clicking one of these items, I would like to drop a pin in the google map. I am having trouble updating the markers on the google map. I can add one marker at initialization of the map, but cannot get new markers to be dropped. Here is my code: https://gist.github.com/aarongirard/32f80f17e19d3e0389da. The issue occurs in the if else clause within the click function.
Any help is appreciated!!
//global variables //google map
var map;
var marker;
var currentMakerli;
function initialize() {
//set latlng of starting window of map
var mapOptions = {
center: { lat: 34.073609, lng: -118.562313},
zoom: 14,
};
//set map using above options and attach to given element
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//construct new marker; constructor takes an object with position and title properties
//get lat long for first marker
var latlng = new google.maps.LatLng(34.073514, -118.562348);
marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Home"
});
//on click of li add new marker or remove if marker already exists
$(".DataList li").click(function(){
//if current marker set to this already
//remove marker
if ( $(this).attr('id') === 'current') {
marker.setMap(null);
$(this).attr('id', '');
} else {
$(this).attr('id','current');
var latlngarr = getLatLngFromString($(this).attr('data-position'));
var lat = latlngarr[0];
var lng = latlngarr[1];
thisLatlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
//marker.setMap(map);
}
});
}
//set map
google.maps.event.addDomListener(window, 'load', initialize);
function getLatLngFromString(string){
var array = string.split(',');
array[0] = parseFloat(array[0]);
array[1] = parseFloat(array[1]);
return array;
}
You must store the marker in a way in which you are able to get a relation between the <li> and the marker, e.g. via $.data
simple example:
function initialize() {
//set latlng of starting window of map
var map = new google.maps.Map($('#map-canvas')[0], {
center: { lat: 34.073609, lng: -118.562313},
zoom: 14,
disableDefaultUI:true
}),
home = new google.maps.Marker({
position: { lat: 34.073514, lng: -118.562348},
map: map,
title: "Home",
icon:'http://maps.google.com/mapfiles/arrow.png'
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push($(".DataList")[0]);
//on click of li add new marker or remove if marker already exists
$(".DataList li").click(function(){
var that=$(this);
//when there is no marker associated with the li we create a new
if(!that.data('marker')){
that.data('marker',new google.maps.Marker({position:(function(ll){
return new google.maps.LatLng(ll[0],ll[1]);
}(that.data('position').split(/,/)))}));
}
var marker=that.data('marker');
//simply check the markers map-property to decide
//if the marker has to be added or removed
if(marker.getMap()){
that.removeClass('current');
marker.setMap(null);
}
else{
that.addClass('current');
marker.setMap(map);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,body,#map-canvas{height:100%;margin:0;padding:0}
.current{background:#f1f1f1;}
.DataList{background:#fff;padding:0;}
.DataList li{cursor:pointer;padding:4px;list-style-position:inside;}
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<ul class="DataList">
<li data-position="34.0717825, -118.567396">Santa Ynez Canyon Park</li>
<li data-position="34.0787989, -118.572502">Palisades Country Estates</li>
<li data-position="34.078375, -118.56098">Highland Recreation Center</li>
</ul>
<div id="map-canvas"></div>
Related to the comments:
You didn't mess up with variable-names, my examples uses less variables, but you may use more variables when you want to.
I prefer to avoid variables when I need to access an object only once.
The marker will be created here(and stored as a property of the <li/>):
//when there is no marker associated with the li we create a new
if(!that.data('marker')){
that.data('marker',new google.maps.Marker({position:(function(ll){
return new google.maps.LatLng(ll[0],ll[1]);
}(that.data('position').split(/,/)))}));
}
The part that splits the data-position-attribute is this:
(function(ll){
return new google.maps.LatLng(ll[0],ll[1]);
}(that.data('position').split(/,/)))
It's a so-called "self-executing anonymous function", which returns the desired value(a LatLng) which will be used as position of the Marker. The splitted data-position-attribute will be used as argument for this function
that.data('position').split(/,/)
getMap() returns whatever the map-property has been set to, either a google.maps.Map-instance or null (when you want to remove the marker or when the property is not set). Although it's not a boolean value it evaluates to either true(when it's a map) or false(when it's null), so it may be used as condition.
The that-variable is always a new variable, that's correct, but it will always be a reference to the same object, the clicked <li/>. The marker has been stored as property of this object.
I am trying to populate a google map with markers. The information for each marker is contained in this array:
[{"id":"1","name":"toler","lng":"110.33929824829102","lat":"-7.779369982234709","created_at":"2014-02-21 16:19:28","updated_at":"2014-02-21 16:19:28"},{"id":"2","name":"hallo :)","lng":"110.36865234375","lat":"-7.797738383377609","created_at":"2014-02-21 16:19:49","updated_at":"2014-02-21 16:19:49"}]
However, my map does not show the markers. I am using this code in my javascript:
getLocations();
function getLocations() {
alert('hello');
$.ajax({
type: "GET",
url: "http://localhost:8888/public/test",
dataType: "jsonp",
success: function(json){
$.each(json, function(i, entry){
PlotMarker(json[i].lat, json[i].long);
});
},
error: function(err){
console.log(err);
}
});
}
function PlotMarker(lat, long){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
map: map,
draggable: false,
animation: google.maps.Animation.DROP
});
markerLocations.push(marker);
}
Is there any way to fix this issue? Calling this url
http://localhost:8888/public/test
returns the JSON shown above.
Any help would be greatly appreciated.
Thanks.
EDIT:
function initialize() {
var markers = [];
var latLng = new google.maps.LatLng(-7.8,110.3666667);
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
Declare your map variable outside of the initialize function. It's the only way that other functions will be able to see it:
var map;
function initialize() {
var markers = [];
var latLng = new google.maps.LatLng(-7.8,110.3666667);
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
Try changing:
PlotMarker(entry.location.lat, entry.location.lng);
to:
PlotMarker(entry.lat, entry.lng);
Try changing this:
PlotMarker(entry.location.lat, entry.location.lng);
To:
PlotMarker(json[i].lat, json[i].lng);
I think it's because of the outer []'s.
The main problem is that getLocations() is called before initialize() is started. You have to comment out getLocations(); and move it to the end of initialize() function.
That is not enough: map definition has to be moved outside of initialize() function and should not be redefined inside initialize() function.
markerLocations, used in PlotMarker(), is not defined. Should be defined as global like map
var map;
var markerLocations = [];
function initialize() {
...
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
...
getLocations();
}
PlotMarker() has to be called like:
PlotMarker(entry.lat, entry.lng);
Are you ever calling your initialize function? Call it right when the page loads.
google.maps.addDomListener(window, 'load', initialize);
as shown here.
What is the sequence of those functions? Which do you call first, and next?
I have encountered this kind of problem and what happens is, the map has not finished loading all the tiles so the markers could not be placed on those and so they do not appear. But when you check in the console, the marker objects are there.
This is how I solved it:
google.maps.event.addListener(map, 'tilesloaded', function() {
plotMarkers();
google.maps.event.clearListeners(map, 'tilesloaded');
});
It assures the map tiles are completely loaded before plotting the markers. In this case, the markers will surely be visible.