Pins missing from Google Maps API display

TLDR:

The problem lies within the var marker = new google.maps.Marker() line. It seems that either the pins are not visible, incorrect, or simply not appearing.

Background:

I have implemented some JavaScript code that utilizes AJAX to fetch data on the 25 nearest businesses from my current location. The AJAX query works fine, and the map centers correctly, but the pins marking the businesses are not showing up.

The $.each() loop iterates as expected and displays the correct data (as evidenced by the console.log output of the business name, latitude, and longitude).

My instinct tells me that I may have overlooked something simple, although I have been unable to identify it so far.

What could be causing this issue?

PS. The sequence of events is as follows:

  1. getCurrentPosition requests the browser for location data and invokes the callback function geo_success()

  2. geo_success() receives the coordinates and initializes the map

  3. After obtaining a map object, we make an AJAX call to the server's /locations/ service to fetch a JSON array of businesses

  4. We then iterate through the data to create markers and add them to the map

I am somewhat suspicious about leaving the maps callback initMap() empty, but I came across example code in the developer's references that does the same, so it should be fine.

Below is the code snippet:

// Footer JS

var wpid = navigator.geolocation.getCurrentPosition(geo_success, geo_error, geo_options);

var geo_options = {
    enableHighAccuracy: true, 
    maximumAge        : 30000, 
    timeout           : 27000
};

var latitude  = 0;
var longitude = 0;

function geo_success(position) {
    console.log(position.coords.latitude, position.coords.longitude);
    latitude = position.coords.latitude;
    longitude = position.coords.longitude;
    console.log("Initializing map at " + latitude + ", " + longitude);

    var myCenter = {lat: latitude, lng: longitude};

    var mapOptions = {
      zoom: 12,
      center: myCenter,
      mapTypeId: 'roadmap'
    };
    
    var map = new google.maps.Map(document.getElementById('map'),
        mapOptions);

    counter = 0;

    $.ajax({
        url:'/locations/',
        data: {
            latitude : latitude,
            longitude : longitude
        },
        dataType: 'json'
        }).done(function(data){
            $.each(data,function(i,item){
                console.log("Adding pin " + i + " for: " + item.label + " @ " + item.latitude + ", " + item.longitude);
                pin = new google.maps.LatLng(parseInt(item.latitude),parseInt(item.longitude));
                var marker = new google.maps.Marker({
                  position: pin,
                  map: map,
                  type:'info'
                });

            })
        });
}

function geo_error() {
    alert("Sorry, no position available.");
}

function initMap() {
}

Answer №1

Perhaps the issue lies in this particular line - try using ParseFloat instead of ParseInt!

Please update the following line:

 pin = new google.maps.LatLng(parseInt(item.latitude), parseInt(item.longitude));

to:

pin = new google.maps.LatLng(parseFloat(item.latitude), parseFloat(item.longitude));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A Guide to Importing CSV Data Into a Datatable

Is there a way to efficiently import data from a CSV file and display it in a table using the datatables plugin? Currently, I have a fixed table structure: <table id="myTable" class="table table-striped" > <thead> ...

background image alteration when scrolling

I've been attempting to change the background image on scroll, but I haven't had any luck finding a guide. So, I'm hoping someone here can help me out. I found a video that showcases exactly what I'm trying to accomplish - https://www.y ...

Node.js Conditional Logic using Javascript

Can a check be implemented for the following scenario? A continuous loop of numbers, such as 1 2 3 4, is being sent to the server. However, I only want each number to be accepted once. Here is my current approach. I believe I am missing one additional c ...

Encountering a Typescript error while attempting to iterate through Enum keys for generating JSX components

I'm really struggling with this problem. Here's a simple enum I have: export enum depositTypes { ACH = 42, Wire = 36, Check = 3, Credit = 2, } I'm trying to create option tags for a select element, like so: Object.keys(depositTyp ...

Generic partial application fails type checking when passing a varargs function argument

Here is a combinator I've developed that converts a function with multiple arguments into one that can be partially applied: type Tuple = any[]; const partial = <A extends Tuple, B extends Tuple, C> (f: (...args: (A & B)[]) => C, ...a ...

Tips on building an immersive interactive panoramic website

I have a vision for a website that will simulate being in a room, where users can explore the space with limited panoramic views - allowing them to look up/down 30 degrees and left/right 45 degrees. In addition, I would like to integrate interactive object ...

Discovering the magic of activating a JavaScript function on jQuery hover

I need to call a JavaScript function when hovering over an li element. var Divhtml='<div>hover</div>'; $('li a').hover(function(){ $(this).html(Divhtml); //I want to trigger hovercall(); wh ...

Enable strict mode for older web browsers

I would like to incorporate the "use strict"; statement into my function, but unfortunately it is not compatible with older browsers such as ie7 and ie8. Is there a workaround to ensure this functionality works in legacy browsers? Could someone please cla ...

Converting an HTML table into an Excel spreadsheet

In the process of developing an application that populates a table based on a JSON dataset, I am seeking a way to store the filtered data into an Excel file or even a CSV. The structure includes two script files - app.js and mainController.js (organized fo ...

Unleashing the potential of extracting the value of a subsequent iteration while within the

Currently, I am facing a dilemma as I am unable to comprehend the logic required to design this algorithm. The problem at hand involves a sequence of images with arrows placed alternatively between each image. The structure appears as follows: Image -> ...

Extract the image URL from a JSON API

I'm struggling to retrieve an image URL from a Wordpress JSON API and populate an image tag with it. Below is the code that isn't working for me: $(document).ready(function() { $.getJSON('http://interelgroup.com/api/get_post/?post_id=46 ...

The function app.post in Express Node is not recognized

I decided to organize my routes by creating a new folder called 'routes' and moving all of them out of server.js. In this process, I created a file named 'apis.js' inside the routes folder. However, upon doing so, I encountered an error ...

Establishing the properties of an object as it is being structured within a nested data format

I am in the process of creating a unique JSON representation, focusing on object composition to directly set key values during composition. However, I've encountered difficulty composing multiple objects in a nested manner. My goal is to find an expr ...

Can an Updatepanel control be added to a webpage using Javascript or JQuery?

I'm currently working on a project that involves allowing users to drag icons representing user controls onto a web page. For the desired functionality, these user controls must be contained within an updatepanel (or a similar AJAX-enabled frame) so ...

What is the best way to create a button with this functionality?

In the form that I have created, it is opened in a bootstrap modal style. This form contains a button that, when clicked, triggers an alert box to appear. The code snippet used for this functionality is as follows: echo "<script>"; echo "alert(&apos ...

Create an asynchronous method within an object-oriented programming (OOP) class

Presenting my Activity class. export class Activity { _name: string _goIn: boolean constructor(name: string) { this._name = name; this._goIn = false; } isGoIn() { return this._goIn; } setGoIn() { // instructions to asyn ...

Efficiently shrink column width in Material-UI's <TableRow/> using ReactJS and Material-UI

At the moment, I am utilizing ReactJS along with Material-UI. One issue I am encountering is that when using Material-UI's <Table>, the columns' width are automatically set based on content which results in all columns having equal width. H ...

Encountering a bad request error while attempting to update a numeric value in MongoDB

I attempted to update a single element in mongodb, specifically a number value. Below is the request sent to the DB: const handleDelivered = (num) =>{ const total = service.quantity; const final = parseInt(total) + num; console.log(tota ...

List of images using React Native's FlatList

Seeking assistance with integrating images into a flatlist grid. I have successfully implemented text but struggling with images stored in the assets folder. The goal is to display separate images from the assets folder within the boxes of the flatlist gr ...

Implementing onbeforeunload event on body tag with jQuery for Chrome and IE browsers

My current system includes a feature where I need to confirm with the user if they really want to leave the page once a dirty flag is set. I have implemented the following code - when viewing in Firefox, I can see that the page source shows the onbeforeun ...